简体   繁体   English

为什么我的循环在数字为 0 时停止?

[英]Why does my loop stop when the number is 0?

 function enigma(inputValue) { var i = 0; while (inputValue) { if (++i == 5) inputValue = 0; } return i; } var whatAmI = enigma(5); console.log(whatAmI);
 <div>Hit F12 and go to the console to view output.</div>

The output I get is 5.我得到的输出是 5。

Why does JavaScript stop the loop if inputValue equals 0?为什么如果inputValue等于 0,JavaScript 会停止循环? Is this because I did not specify that as the condition in the while loop?这是因为我没有将其指定为 while 循环中的条件吗?

0 is false. 0 是假的。 You can check here你可以在这里查看

This explains the basics of a while loop.这解释了 while 循环的基础知识。 The condition within the while loop checks if it is truthy/falsy. while 循环中的条件检查它是否为真/假。 When i is equal to 5, the input is 0, which causes the condition to be false.当 i 等于 5 时,输入为 0,这会导致条件为假。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while

If you want to see some other crazy Javascript, check out these truthy/falsy examples.如果您想查看其他一些疯狂的 Javascript,请查看这些真/假示例。

http://blog.falafel.com/the-truth-about-false-in-javascript/http://blog.falafel.com/the-truth-about-false-in-javascript/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM