我正在尝试在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++;
}
答案 0 :(得分:1)
在增加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++;
}
答案 1 :(得分:1)
每次使用关键字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++;
}