奇怪的内部循环不执行某些迭代 [英] Weird inner loop not executing certain iterations
问题描述
我试图回答这个问题,在那里我遇到了奇怪的循环条件。
$ b $ pre $ code> for(index1 = 1; index1 <8; index1 ++){
var op =' #';
for(index2 = index1; index2 - 1; index2--){//这个循环对我来说很奇怪
op = op +'#';
}
console.log(op);
$ / code>
在检查每个外循环迭代的内循环有多少次迭代得到这个:
$ b
看,它记录 0,1,2,3,4,5,6
。
我的问题是:
$ b
内循环是不是在第一个外循环迭代迭代,因为
index2 - 1
等于零,这是假的?
内部循环是不是迭代在第一个外部循环迭代,因为index2 - 1等于零,这是假的?
这是正确的。任何提供给条件的错误值立即停止循环。
Falsey值是 0
, NaN
, null
, undefined
,
和 false
。
I was trying to answer this question where I encountered a weird loop condition.
for (index1 = 1; index1 < 8; index1++) {
var op = '#';
for (index2 = index1; index2 - 1; index2--) { //this loop is weird to me
op = op + '#';
}
console.log(op);
}
Upon checking how many iterations the inner loop is making for each outer loop iteration I get this:
var x = 0;
for (index1 = 1; index1 < 8; index1++) {
//var op = '#';
for (index2 = index1; index2 - 1; index2--) {
var log = {};
log.a = x; //check value before increment
x++;
log.b = x; //check value after increment
console.log(`outer: ${index1}, inner: ${index2}`, log);
}
console.log(x);
x = 0;
//console.log(op);
}
As you can see, it logs 0, 1, 2, 3, 4, 5, 6
.
My questions is:
Is the inner loop not iterating on the first outer loop iteration because
index2 - 1
is equal to zero, which is falsy?
Is the inner loop not iterating on the first outer loop iteration because index2 - 1 is equal to zero, which is falsy?
That's correct. Any falsey value provided to the condition to the loop immediately halts the loop.
Falsey values are 0
, NaN
, null
, undefined
, ""
and false
.
这篇关于奇怪的内部循环不执行某些迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!