如何在内置的for-in中跳转到javascript中的下一个?

Ram*_*yer 24 javascript for-loop for-in-loop

我有一个简短的javascript代码,我需要在for循环中跳到下一个....见下文:

var y = new Array ('1', '2', '3', '4');
for (var x in y) {
   callFunctionOne(y[x]);
   while (condition){
       condition = callFunctionTwo(y[x]);
       //now want to move to the next item so 
       // invoke callFunctionTwo() again...
   }
}
Run Code Online (Sandbox Code Playgroud)

希望保持简单,因此语法可能没有错误.

Ble*_*der 46

不要使用迭代遍历数组for...in.该语法用于迭代对象的属性,这不是您所追求的.

至于你的实际问题,你可以使用continue:

var y = [1, 2, 3, 4];

for (var i = 0; i < y.length; i++) {
    if (y[i] == 2) {
        continue;
    }

    console.log(y[i]);
}
Run Code Online (Sandbox Code Playgroud)

这将打印:

1
3
4
Run Code Online (Sandbox Code Playgroud)

实际上,看起来你想要摆脱while循环.你可以用break它:

while (condition){
    condition = callFunctionTwo(y[x]);
    break;
}
Run Code Online (Sandbox Code Playgroud)

看看do...while循环也是如此.

  • 我对这是这个问题唯一得到高度评价的答案感到有点不高兴。在我个人看来,使用“for..of”将是一个更好的选择,因为它是一种更可靠、更现代的循环迭代方式,同时保留跳过或取消循环的能力。 (2认同)