// 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);});