
forEach是不能通过break或者return跳出循环的,一般跳出循环的方式为抛出异常:
try {
let array = [1, 2, 3, 4]
array.forEach((item, index) => {
if (item === 3) {
throw new Error('end')//报错,就跳出循环
} else {
console.log(item)
}
})
} catch (e) {
}
这种写法反而很麻烦。
解决方式
1. 使用 every 替代:
let array = [1, 2, 3, 4]
array.every((item, index) => {
if (item === 3) {
return true
} else {
console.log(item)
}
})
2.自己写一个😁
//可跳出循环的数组遍历
Array.prototype.loop = function(cbk) {
//判断当前数组是否为空
if (this?.length) {
for (let i = 0; i < this.length; i++) { let stop = cbk(this[i], i, this) //判断是否停止循环 if (stop) { break } } } } let array = [1, 2, 3, 4] array.loop ((item, index) => {
if (item === 3) {
return true
} else {
console.log(item)
}
})