面试主题:【循环】【forEach】【JS】
======================================================
问:forEach如何退出循环
答:无法常规退出循环,需要使用
try { throw new Error(msg) } catch (error) {}捕获异常终止
======================================================
测试思路:
常规循环
捕获异常退出循环
常规退出循环:return
常规退出循环:break
/** * forEach如何终止循环 */ let demo = (window.demo = {}), ary = [2, 4, 6, 8], newAry = []; demo.Constants = { LAST_ITEM_INDEX: 1, //用于获取数组最后一个元素 EQUEAL_CONDITION: "满足条件,跳出循环" //异常信息 }; demo.commonForEach = (ary, newAry) => { if (!(ary instanceof Array)) return; ary.forEach(function(item) { newAry.push(item); }); console.log("循环结束,newAry:", newAry); }; demo.commonForEach(ary, newAry);
常规循环结果:

/** * forEach如何终止循环 */ let demo = (window.demo = {}), ary = [2, 4, 6, 8], newAry = []; demo.Constants = { LAST_ITEM_INDEX: 1, //用于获取数组最后一个元素 EQUEAL_CONDITION: "满足条件,跳出循环" //异常信息 }; demo.tryCatchForEach = (ary, newAry, breakItem) => { if (!(ary instanceof Array)) return; if (Boolean(newAry.length)) { newAry = []; } let breakItemValue = breakItem || ary.length - demo.Constants.LAST_ITEM_INDEX; try { ary.forEach(function(item) { if (item == breakItemValue) { throw new Error(demo.Constants.EQUEAL_CONDITION); } newAry.push(item); }); console.log("循环结束,newAry:", newAry); } catch (error) { if (!Boolean(newAry.length)) { console.log(error.message); } else { console.log("循环被终止,newAry:", newAry); } } }; demo.tryCatchForEach(ary, newAry, ary[1]); demo.tryCatchForEach(ary, newAry, ary[0]);
捕获异常退出循环结果:

/** * forEach如何终止循环 */ let demo = (window.demo = {}), ary = [2, 4, 6, 8], newAry = []; demo.Constants = { LAST_ITEM_INDEX: 1, //用于获取数组最后一个元素 EQUEAL_CONDITION: "满足条件,跳出循环" //异常信息 }; demo.returnForEach = (ary, newAry, breakItem) => { if (!(ary instanceof Array)) return; if (Boolean(newAry.length)) { newAry = []; } let breakItemValue = breakItem || ary.length - demo.Constants.LAST_ITEM_INDEX; ary.forEach(function(item) { if (item == breakItemValue) { return; } newAry.push(item); }); console.log("循环结束,newAry:", newAry); }; demo.returnForEach(ary, newAry, ary[1]);
常规退出循环-return结果:

/** * forEach如何终止循环 */ let demo = (window.demo = {}), ary = [2, 4, 6, 8], newAry = []; demo.Constants = { LAST_ITEM_INDEX: 1, //用于获取数组最后一个元素 EQUEAL_CONDITION: "满足条件,跳出循环" //异常信息 }; demo.berakForEach = (ary, newAry, breakItem) => { if (!(ary instanceof Array)) return; if (Boolean(newAry.length)) { newAry = []; } let breakItemValue = breakItem || ary.length - demo.Constants.LAST_ITEM_INDEX; ary.forEach(function(item) { if (item == breakItemValue) { break; } newAry.push(item); }); console.log("循环结束,newAry:", newAry); }; demo.berakForEach(ary, newAry, ary[1]);
常规退出循环-break:

浙公网安备 33010602011771号