国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JavaScript使用類似break機制中斷forEach循環的方法

2024-05-06 15:27:58
字體:
來源:轉載
供稿:網友

JavaScript數組對象,有一個forEach方法,可枚舉每一個數組元素,但并不支持類似for循環的break語法,中斷循環:

[1,2,3].forEach(function(item) {  // if(!item) break; 不支持});

解決辦法,可拋出一個特殊異常,來中斷forEach循環,原理:

var BreakException = {};try {[1, 2, 3].forEach(function(el) {console.log(el);if (el === 2) throw BreakException;});} catch (e) {if (e !== BreakException) throw e;}

也可復寫forEach方法:

// Use a closure to prevent the global namespace from be polluted.(function() {// Define StopIteration as part of the global scope if it// isn't already defined.if(typeof StopIteration == "undefined") {StopIteration = new Error("StopIteration");}// The original version of Array.prototype.forEach.var oldForEach = Array.prototype.forEach;// If forEach actually exists, define forEach so you can// break out of it by throwing StopIteration. Allow// other errors will be thrown as normal.if(oldForEach) {Array.prototype.forEach = function() {try {oldForEach.apply(this, [].slice.call(arguments, 0));}catch(e) {if(e !== StopIteration) {throw e;}}};}})();

使用

// Show the contents until you get to "2".[0,1,2,3,4].forEach(function(val) {if(val == 2)throw StopIteration;alert(val);});

總結

以上所述是小編給大家介紹的JavaScript使用類似break機制中斷forEach循環的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對錯新站長站網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 茂名市| 湖州市| 岳阳市| 漯河市| 积石山| 南投县| 大冶市| 黑河市| 桦南县| 肇州县| 孟州市| 阿克陶县| 正镶白旗| 江达县| 怀安县| 惠东县| 陈巴尔虎旗| 石城县| 柘城县| 安化县| 南涧| 晋中市| 田阳县| 满洲里市| 康乐县| 安阳县| 曲松县| 方山县| 邓州市| 鹰潭市| 龙山县| 邵阳市| 蒲江县| 扶风县| 晴隆县| 建湖县| 阳新县| 湄潭县| 定州市| 博野县| 天气|