众所周知,forEach循环是无法中途跳出循环的,有点同学说不是可以通过抛出错误跳出循环吗?是的。抛出异常是广为流传的一种方法,结果是我们想要,但是你看代码,哪个正常人会这样写代码?是非forEach不用吗?还是其他的循环关键字不配呢。
const list = [1, 2, 3, 4, 5, "a", "b", "c", "d", "e"];
try {
list.forEach((itm) => {
if (itm === "c") {
throw new Error("exit");
}
console.log(itm);
});
} catch (e) {
// console.log(e);
}
const list = [1, 2, 3, 4, 5, "a", "b", "c", "d", "e"];
Object.assign(list).forEach((itm, idx, arr) => {
if (itm == "c") {
arr.splice(idx, arr.length - idx);
}
console.log(itm);
});
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有