forEach踩坑
小于 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