停止 forEach 的 3 种方法
我在网上查阅了很多一般都是以上这种抛出错误的方法来终止循环。虽然这种做法都不对,但是也能解决那些面试官的一些刁难。但是这样会影响到原数组,但是也实现了我们的目的。结合这种方式还有以下方法。思路也是跟方法二一样。
文章共246字 · 阅读需要大约1分钟
一键AI生成摘要,助你高效阅读
问答
·
1第一种抛出错误
const array = [ -3, -2, -1, 0, 1, 2, 3 ]
try {
array.forEach((it) => {
if (it >= 0) {
console.log(it)
throw Error(`We've found the target element.`)
}
})
} catch (err) {
}
我在网上查阅了很多一般都是以上这种抛出错误的方法来终止循环
第二种
let arr = [1, 2, 3, 4, 5]
arr.forEach(item => {
if (item > 2) {
arr.length = 0
}
console.log(item);
})
运行结果如下
但是这样会影响到原数组,但是也实现了我们的目的
结合这种方式还有以下方法
思路也是跟方法二一样
const array = [ -3, -2, -1, 0, 1, 2, 3 ]
array.forEach((it, i) => {
if (it >= 0) {
console.log(it)
// Notice the sinful line of code
array.splice(i + 1, array.length - i)
}
})
虽然这种做法都不对,但是也能解决那些面试官的一些刁难
更多推荐
已为社区贡献1条内容
所有评论(0)