当while条件中有0时,while循环会执行吗? [重复]

问题描述 投票:3回答:5

这个问题在这里已有答案:

我们来看看示例代码:

 var limit = 3;
 while(limit--){
   console.log(limit);
   if(limit){
     console.log("limit is true");
   }else{
     console.log("limit is false")
   }
 }

输出将是:

2
"limit is true"
1
"limit is true"
0
"limit is false"

有一个0,这意味着在最后一次条件时是假的。为什么最后一次循环会执行?

javascript while-loop
5个回答
8
投票

limit--这是一个后减量。因此,当limit1时,它会在true内部解析为while,然后它实际上会减少,因此当你打印时它是0


3
投票
while(limit--) 

等于

while(limit){
    limit = limit -1;
}

因此,while表达式的限制是3到1,而在括号中,limit是从2到0,因此将执行'limit is false'。如果你期望'limit is false'不执行,你可以用limit--替换--limit


3
投票

当您使用后增量时,它将首先检查条件然后将对该变量执行减量,因此这里(limit--)将被视为while(limit)。

DRY RUN:

var limit = 3;

第一次:

while(limit--){     //check limit while limit = 3 returns true and then decrement by 1 
   console.log(limit);  //so now print limit as 2
   if(limit){  //check limit while limit = 2
     console.log("limit is true");  //so now print this one
   }else{
     console.log("limit is false")
   }
 }

第二次:

while(limit--){     //check limit while limit = 2 returns true and then decrement by 1 
   console.log(limit);  //so now print limit as 1
   if(limit){     //check limit while limit = 1
     console.log("limit is true");  //so now print this one
   }else{
     console.log("limit is false")
   }
 }

第三次:

while(limit--){     //check limit while limit = 1 returns true and then decrement by 1 
   console.log(limit);  //so now print limit as 0
   if(limit){     //check limit while limit = 0
     console.log("limit is true");  
   }else{
     console.log("limit is false")  //so now print this one
   }
 }

第四次:

它不会进入while循环,因为now limit = 0


0
投票

在几种语言中,0值被视为false值。

limit--在被while条件评估后也会减少。


0
投票

这是一个很好的方式来看待它。我们正在查看一个数字,看看它是否在0之前,如果我们正在拿走1然后再次循环,否则我们就会停在那里。

let three = 3, two = 2, one = 1, zero = 0;

console.log('3--: ' + (three-- > 0));
console.log('2--: ' + (two-- > 0));
console.log('1--: ' + (one-- > 0));
console.log('0--: ' + (zero-- > 0));
© www.soinside.com 2019 - 2024. All rights reserved.