让我们看一下示例代码:
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,这意味着在最后一次条件时为假。为什么最后一次循环会执行?
答案 0 :(得分:8)
limit--
这是一个减员额。因此,当limit
位于1
时,它会在true
内解析为while
,然后它实际上会递减,因此当您打印它时0
。
答案 1 :(得分:3)
while(limit--)
等于
while(limit){
limit = limit -1;
}
所以表达式的限制是从3到1,
在括号中,limit从2到0,因此将执行'limit is false'。
如果您预计'limit is false'未执行,则可以将limit--
替换为--limit
答案 2 :(得分: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
答案 3 :(得分:0)
在多种语言中,0
值被视为false
值。
同样limit--
在被while
条件评估后进行减量。
答案 4 :(得分: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));