为什么下面的JavaScript代码无限循环?

问题描述 投票:-1回答:2

我想用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++;
}
javascript
2个回答
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++;
}

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++;
}
© www.soinside.com 2019 - 2024. All rights reserved.