为什么以下Javascript代码无限循环?

时间:2019-02-05 05:33:22

标签: javascript

我正在尝试在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++;
}

2 个答案:

答案 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++;
}