我想用while循环中的Javascript continue
语句,但它无限循环
你能解释一下吗?
var john = ['john', 'smith', 1990, 'designer', false, 'blue' ];
var i = 0;
while ( i < john.length) {
if( typeof john[i] !== 'string') continue;
console.log( john[i]);
i++;
}
每当你使用continue
你跳过它下面的代码的其余部分和跳跃回到你while
循环顶部的关键字。这意味着,一旦你i++
continue
永远达不到,所以,你总是会看你的数组中的整数1990
。因此continue
将永远被称为你的if语句将被卡住看起来像这样:
if(typeof 1990 !=== 'string') {
// true so code will fire
continue; // you reach continue so your loop runs again, running the same if statement check as you haven't increased 'i' (so it checks the same element)
}
// all code below here will not be run (as 'continue' is used above)
相反,你需要在你的if
声明,其外部递增。让你看看你的数组中的下一个值:
var john = ['john', 'smith', 1990, 'designer', false, 'blue' ];
var i = 0;
while ( i < john.length) {
if( typeof john[i] !== 'string') {
i++; // go to next index
continue;
}
console.log( john[i]);
i++;
}
您递增continue
前值已经写i
。
i
之前,您应该增加continue
的价值,就像这样:
var john = ['john', 'smith', 1990, 'designer', false, 'blue' ];
var i = 0;
while ( i < john.length) {
if( typeof john[i] !== 'string') {
i++;
continue;
}
console.log( john[i]);
i++;
}