我正在网上课程上练习Javascript。这只是第一个,我遇到了问题,所以在进步之前我真的想了解它。
问题是:
complete the while loop in the editor so it will print out "I'm learning while loops!". Do this by adding the condition between the parentheses—don't change line 5, or you could get an infinite loop!
代码是:
var understand = true;
while(){
console.log("I'm learning while loops!");
understand = false;
}
我尝试将其添加到条件中:
while(understand === 0){
但我收到此错误
哎呀,再试一次。看起来你没有将字符串打印到控制台。检查循环语法!
在我的情况下,我做错了什么?有人可以详细说明,所以我可以从中学到关键的基础知识。谢谢!
本练习前的例子:
var coinFace = Math.floor(Math.random() * 2);
while(coinFace === 0){
console.log("Heads! Flipping again...");
var coinFace = Math.floor(Math.random() * 2);
}
console.log("Tails! Done flipping.");
编辑---更新:
You may have noticed that when we give a variable the boolean value true, we check that variable directly—we don't bother with ===. For instance,
var bool = true;
while(bool){
//Do something
}
is the same thing as
var bool = true;
while(bool === true){
//Do something
}
but the first one is faster to type. Get in the habit of typing exactly as much as you need to, and no more!
If you happen to be using numbers, as we did earlier, you could even do:
答案 0 :(得分:2)
它是while(understand === true)
因为循环将在第一次触发,因为understand
已设置为true。然后,当它触发时,它会将understand
设置为假 - 所以下次尝试触发循环时,条件将失败并且不会继续。这样,您就可以执行一次循环 - 因此只打印一次。
答案 1 :(得分:0)
如果您的代码看起来像这样
while(true){
console.log("I'm learning while loops!");
understand = false;
}
你会得到一个无限循环!循环将继续前进,因为条件总是为真。现在,如果只有某种方式,如条件中的变量,则使条件为假。