JavaScript-怎么跳出Array.forEach()


JavaScript-怎么跳出Array.forEach()

forEach()会遍历完整个数组,不会中途退出

抛出异常

function foreach(a, f, t) {
  try {
    a.forEach(f, t)
  }
  catch (e) {
    if (e === foreach.break) return;
    else throw e;
  }
}

foreach.break = new Error('StopInteration');

arr = [1, 2, 3, 4, 5]

foreach(arr, x => { if (x === 3) throw foreach.break; else console.log(x) })

//输入 1,2

使用forEach的第二个参数

[1, 2, 3, 4].forEach(x => {
  if (this.break == true) {
    return;
  }
  if (x === 2) this.break = true;
  console.log(x)
}, {})

改变数组本身

arr = [1, 2, 3, 4, 5]

arr.forEach((v, index) => {
  if (v > 2) {
    arr.splice(index, arr.length - index)
  }
  console.log(v)
})

//输出 1,2,3

放大招了

用some() ,for循环不香吗??


文章作者: 木叶勇
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 木叶勇 !
 上一篇
调试-VSCode 调试-VSCode
VSCode调试在nodejs中调试 点击图标 编辑或新建配置文件 点击编辑的图标 ​ 进入编辑配置文件的文件(没有配置文件会新建) 编辑配置文件 进行调试 单击F5进行调试,在代码的左侧鼠标右键单击添加断点
2020-04-19
下一篇 
源码-V8sort 源码-V8sort
document.querySelectorAll('.github-emoji') .forEach(el => { if (!el.dataset.src) { return
2020-04-19
  目录