最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript使用類似break機(jī)制中斷forEach循環(huán)的方法

 更新時(shí)間:2018年11月13日 16:41:53   作者:ourjs  
這篇文章主要介紹了JavaScript使用類似break機(jī)制中斷forEach循環(huán)的方法,需要的朋友可以參考下

JavaScript數(shù)組對(duì)象,有一個(gè)forEach方法,可枚舉每一個(gè)數(shù)組元素,但并不支持類似for循環(huán)的break語(yǔ)法,中斷循環(huán):

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

解決辦法,可拋出一個(gè)特殊異常,來(lái)中斷forEach循環(huán),原理:

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

也可復(fù)寫(xiě)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);
});

總結(jié)

以上所述是小編給大家介紹的JavaScript使用類似break機(jī)制中斷forEach循環(huán)的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論

太湖县| 焉耆| 房产| 麦盖提县| 福建省| 咸阳市| 资兴市| 连江县| 长沙县| 林周县| 万宁市| 奈曼旗| 饶阳县| 北京市| 汉中市| 桂阳县| 新泰市| 广南县| 莱州市| 辽源市| 乌鲁木齐市| 三亚市| 瑞金市| 阿荣旗| 轮台县| 浦北县| 吉安市| 镇康县| 漳平市| 淳安县| 肥乡县| 双牌县| 鄱阳县| 买车| 遵义县| 永泰县| 武安市| 平塘县| 东至县| 怀仁县| 台北市|