跳至主要內容

forEach踩坑

zfh小于 1 分钟约 181 字...

开始在项目中使用了forEach来进行循环遍历,当某一项符合条件时,返回false,否则返回true,类似以下代码:

const arr = [
  {
    type: '1',
    name: 'test1',
  },
  {
    type: '2',
    name: 'test2',
  },
]

function test2() {
  arr.forEach((item) => {
    if (item.type === '1') {
      return false
    } else {
      return true
    }
  })
}

后来查阅文档了解到除了抛出异常以外,没有办法中止或跳出 forEach() 循环(break,continue)

如果要实现预期的功能,需要抛出异常来终止循环:

  const arr = [
        {
          type: '1',
          name: 'test1',
        },
        {
          type: '2',
          name: 'test2',
        },
      ]

      function test(type) {
        try {
          arr.forEach((item) => {
            if (item.type === type) {
              throw new Error('not all in') // 抛出异常
            }
          })
        } catch (e) {
          if (e.message == 'not all in') {
            return true // 这里捕获异常并返回
          }
        }
        return false
      }

      console.log(test('1')) // true
      console.log(test('4')) // false
上次编辑于:
本站勉强运行 小时
本站总访问量
網站計數器