如何中断数组的迭代

3 阅读1分钟

废话不多说,直接上代码

使用 try...catch 的方式

try {
  [1, 2, 3, 4, 5].forEach(function(item) {
    if (item=== 2) throw item;
    console.log(item);
  });
} catch (e) {}

可以使用一些其他的数组遍历方式

every在碰到return false的时候,中止循环。

var a = [1, 2, 3, 4, 5]
a.every(item => {
    console.log(item); //输出:1,2
    if (item === 2) {
        return false
    } else {
        return true
    }
})

some在碰到return ture的时候,中止循环。

var a = [1, 2, 3, 4, 5]
a.some(item => {
    console.log(item); //输出:1,2
    if (item === 2) {
        return true
    } else {
        return false
    }
})