JavaScript中如何中断forEach循环

简介: 先来看下forEach的实现 // Production steps of ECMA-262, Edition 5, 15.4.4.18// Reference: http://es5.github.

先来看下forEach的实现

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {

  Array.prototype.forEach = function(callback, thisArg) {

    var T, k;

    if (this === null) {
      throw new TypeError(' this is null or not defined');
    }

    // 1. Let O be the result of calling toObject() passing the
    // |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get() internal
    // method of O with the argument "length".
    // 3. Let len be toUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If isCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== "function") {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let
    // T be undefined.
    if (arguments.length > 1) {
      T = thisArg;
    }

    // 6. Let k be 0
    k = 0;

    // 7. Repeat, while k < len
    while (k < len) {

      var kValue;

      // a. Let Pk be ToString(k).
      //    This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty
      //    internal method of O with argument Pk.
      //    This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal
        // method of O with argument Pk.
        kValue = O[k];

        // ii. Call the Call internal method of callback with T as
        // the this value and argument list containing kValue, k, and O.
        callback.call(T, kValue, k, O);
      }
      // d. Increase k by 1.
      k++;
    }
    // 8. return undefined
  };
}

基本用法:

arr.forEach(callback[, thisArg]),callback会接收到三个参数:currentValue、index、array
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.forEach(function(value, index, _ary) {
    console.log(index + ": " + value);
    return false;
});

// logs:

0: JavaScript
1: Java
2: CoffeeScript
3: TypeScript

 

使用some函数

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.some(function (value, index, _ary) {
    console.log(index + ": " + value);
    return value === "CoffeeScript";
});

// logs:

0: JavaScript
1: Java
2: CoffeeScript

 

使用every函数

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

ary.every(function(value, index, _ary) {
    console.log(index + ": " + value);
    return value.indexOf("Script") > -1;
});

// logs:

0: JavaScript
1: Java

使用fo..of

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let el of arr) {
  console.log(el);
  if (el === 5) {
    break;
  }
}
// logs:
0
1
2
3
4
5

 

而如果forEach想实现类似every、some函数的效果该如何做呢?

在stackoverflow上得票比较高的有如下几类方法 :

1、循环外使用try.. catch,当需要中断时throw 一个异常,然后catch进行捕获;

2、重写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;
}
 
// 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);
});

 

参考链接:

http://dean.edwards.name/weblog/2006/07/enum/

http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of


目录
相关文章
|
21天前
|
JavaScript 前端开发 安全
JavaScript中的循环控制:while、do-while与for详解
【4月更文挑战第7天】本文探讨JavaScript的三种主要循环结构:while、do-while和for。while循环在满足条件时执行代码块,注意避免无限循环;do-while循环至少执行一次,适合先执行后判断的场景;for循环结合初始化、条件和迭代,适合遍历。理解每种循环的特点和适用场景,结合编程技巧,如使用break和continue,选择合适的循环方式,能提升代码效率和可读性。记得关注循环性能和避免不必要的计算。
18 0
|
26天前
|
JavaScript 前端开发 索引
问js的forEach和map的区别
JavaScript中的`forEach`和`map`都是数组迭代方法。`forEach`遍历数组但不修改原数组,无返回值;它接受回调函数处理元素。`map`则遍历数组并返回新数组,新数组元素为回调函数处理后的结果。两者都接收元素、索引和数组作为回调函数参数。
21 7
|
28天前
|
JavaScript
在循环内错误使用函数定义(js的问题)
在循环内错误使用函数定义(js的问题)
11 0
|
29天前
|
JavaScript
JS使用循环求100内奇数之和
JS使用循环求100内奇数之和
16 1
|
1月前
|
JavaScript 前端开发
JS——while 循环和 do while 循环:究竟有什么区别?
JS——while 循环和 do while 循环:究竟有什么区别?
18 1
|
2天前
|
JavaScript 前端开发
JavaScript 条件循环语句(for 循环)
JavaScript 条件循环语句(for 循环)
|
5天前
|
前端开发 JavaScript 开发者
遍历指南:JavaScript 中的 for、for-in、for-of 和 forEach 循环详解
遍历指南:JavaScript 中的 for、for-in、for-of 和 forEach 循环详解
15 3
|
9天前
|
JavaScript 索引
JS 几种循环遍历
JS 几种循环遍历
9 0
JS 几种循环遍历
|
14天前
|
JavaScript 前端开发
js中的while循环和do while循环的区别
js中的while循环和do while循环的区别
18 8
|
2月前
|
开发框架 JavaScript 前端开发
描述JavaScript事件循环机制,并举例说明在游戏循环更新中的应用。
JavaScript的事件循环机制是单线程处理异步操作的关键,由调用栈、事件队列和Web APIs构成。调用栈执行函数,遇到异步操作时交给Web APIs,完成后回调函数进入事件队列。当调用栈空时,事件循环取队列中的任务执行。在游戏开发中,事件循环驱动游戏循环更新,包括输入处理、逻辑更新和渲染。示例代码展示了如何模拟游戏循环,实际开发中常用框架提供更高级别的抽象。
14 1