splice变相跳出forEach循环
25-04-07
slbcun
705℃
0
众所周知,forEach循环是无法中途跳出循环的,有点同学说不是可以通过抛出错误跳出循环吗?是的。抛出异常是广为流传的一种方法,结果是我们想要,但是你看代码,哪个正常人会这样写代码?是非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); }
splice变相跳出循环
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); });