JavaScript while循环与布尔变量作业疑问求助
关于JavaScript while循环作业的疑问
我之前通过视频学了for和while循环的基础结构,比如标准的while循环是这样的:
while(condition is true) { //do something }
但作业里的题目和学的内容脱节,完全不知道怎么下手,导师的回答还更模糊,只能来求助。
问题1:基于布尔变量的while循环实现
作业给出了一种用布尔变量控制的while循环写法,要求补全代码:
// Another way to write a while loop is to have a boolean variable // where the condition goes and then test every time if you need to // change the boolean to false. // Below we have a variable lessThan5 and it is set to true. // Create a loop that tests if our variable 'j' is less than 5. // If it is less than 5 then Increment it by 1. If it is not // less than 5 then set our lessThan5 variable to be false. let lessThan5 = true; let j = 0; while(lessThan5) { }
我没学过用布尔变量来控制while循环的写法,作业的指令也说不清楚,不知道怎么写循环体里的内容。
问题2:按指定次数循环的while循环实现
作业先给了一个猜数字游戏的示例代码:
// Example of what the number game would look like: // Couple things to note: // Math is a built in object in javascript. // Math.round() will round a decimal number to a whole number. // Math.random() returns a decimal number between 0 to 1. // (But not including 1) function guessNumberGame(guess) { let guessing = true; let number = Math.round(Math.random() * 100); while(guessing) { if(guess === number) { guessing = false; } else { guess = Number(prompt("That number didn't work. Try again: ")); } } }
然后是Problem 3的要求:
// Problem 3 // We will give you a number through the 'num' parameter // Create a while loop that will loop 'num' amount of times. // For example if num is 3 then your while loop should loop 3 times // If num is 20 then the loop should loop 20 times. // Increment k every loop. let k = 0; function keepLooping(num) { }
我完全看不出这个问题和前面的猜数字示例有什么关联,也不知道怎么写这个循环来达到指定的次数。
之前学习进度一直没问题,现在突然卡在这里,周围也没人提相关疑问,感觉特别困惑。
内容的提问来源于stack exchange,提问作者mosty frug
相关产品推荐
相关产品推荐

