简体   繁体   English

当条件检查变量变为0时,为什么while循环停止?

[英]Why does the while loop stop when condition check variable becomes 0?

Could someone explain me what happens down below? 有人可以解释一下下面发生的事情吗?

var i = 5;
while(--i){
  console.log(i);
}

The thing is the while loop goes until 1 (console logs 4,3,2,1) 问题是while循环一直到1(控制台日志4,3,2,1)

I know that if I check 1 or 0 for true I will get the following result 我知道如果我检查1或0为真,我将得到以下结果

0 == true > false 0 ==真>假

1 == true > true 1 ==真>真

What I dont understand is what happens when the number is something like 4? 我不明白的是,当数字为4时会发生什么? How does that even work? 那怎么工作?

Since checking 4 for true will deliver the following result 由于检查4为true将提供以下结果

4 == true > false 4 ==真>假

As commented above: 如上文所述:

4 is a truthy value in javascript: 4是javascript中的真实值:

if (4) {
    console.log(true);    
} else {
    console.log(false);
}

this will print true 这将打印true

Another way to see this: 另一种查看方式:

0 and true = false
1 and true = true
4 and true = true

Documentation for truthy: https://developer.mozilla.org/en/docs/Glossary/Truthy 真实性文档: https : //developer.mozilla.org/en/docs/Glossary/Truthy

In JavaScript, a truthy value is a value that translates to true when evaluated in a Boolean context. 在JavaScript中,真实值是在布尔上下文中求值时转换为true的值。 All values are truthy unless they are defined as falsy (ie, except for false, 0, "", null, undefined, and NaN). 除非将它们定义为虚假,否则所有值都是真实的(即,除了false,0,“”,null,undefined和NaN外)。

The reason that 4 != true is that the true value is coerced into a number. 4 != true的原因是将true值强制转换为数字。 So infact 4 == true + true + true + true 所以4 == true + true + true + true

Any non-zero number is treated as TRUE. 任何非零数字都将被视为TRUE。

So in your loop, i starts as 5. On the first iteration i is reduced by 1 (by the --i ), and the result (4) is tested to be TRUE. 因此,在您的循环中, i从5开始。在第一次迭代中, i减少了1(由--i ),并且测试结果(4)为TRUE。 Thus it enters the WHILE loop and logs the value of i (4). 因此,它进入WHILE循环并记录i (4)的值。 The WHILE loop then returns to start and reduces the value of i by 1 again to become 3. This is also treated as TRUE and thus enters the loop again. 然后WHILE循环返回开始,并将i的值再次减小1变为3。这也被视为TRUE,因此再次进入循环。

Only once i reaches 0 does it get treated as FALSE, and thus exits the WHILE loop. 只有当i达到0时,它才会被视为FALSE,从而退出WHILE循环。

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

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