在javascript的某些条件下重复循环迭代的最干净的方式?



这可以很容易地完成常规的for(;;)循环,但我喜欢使用for (a of b)循环,我想知道什么是最干净的方式来重复迭代?

类似:

for (const item of array){
if (something){
//repeat current iteration and don't go further down
}    
//do something
}

可以取while语句

for (const item of array) {
while (something) {
//repeat current iteration and don't go further down
}    
//do something
}

使用总是假的do..while怎么样?

for (const item of [1, 2, 3, 4]) {
do {
const result = processItem(item);
// will call processItem again for the same item if someCondition returns
// truthy. Otherwise will start processing next item from the array
if (someCondition(result)) continue;
} while (0);
}

试试这个:

restartTheLoop:
while (true) {
for (const item of array){
if (somethingHappend){
continue restartTheLoop; //start all over again
}
//do stuff
}
break;
}

如果somethingHappend为真,continue restartthelloop将在下一次while循环的迭代中转到continue语句。然后像你希望的那样立即开始for循环。如果for迭代结束(没有somethingHappend的值为true), break语句将从包含while循环中跳出。

最新更新