先来看下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

JavaScript中如何中断forEach循环的更多相关文章

  1. JavaScript 中的12种循环遍历方法

    原文:JavaScript 中的12种循环遍历方法 题目:请介绍 JavaScript 中有哪些循环和遍历的方法,说说它们的应用场景和优缺点? 1.for 循环 let arr = [1,2,3];f ...

  2. JavaScript中的for in循环

    在学习AJAX的时候,发现JavaScript中for in循环,这种循环对于遍历JSON是很好用的.于是写下了这篇博文 作用 for in循环本质上是forEach循环,它主要有两个作用 遍历数组 ...

  3. 理解 JavaScript 中的 for…of 循环

    什么是 for…of 循环 for...of 语句创建一个循环来迭代可迭代的对象.在 ES6 中引入的 for...of 循环,以替代 for...in 和 forEach() ,并支持新的迭代协议. ...

  4. 好文:javascript中的四种循环

    https://juejin.im/entry/5a1654e951882554b8373622?utm_medium=hao.caibaojian.com&utm_source=hao.ca ...

  5. javascript中的for in循环和for in循环的使用陷阱

    javascript中的for循环和for...in循环还是有些区别的,比如定义一个数组,然后用for..in循环输出 var array=[1,2,3,4,5,6]; for(var s in ar ...

  6. Javascript中快速退出多重循环的技巧

    在双重循环或多重循环中判断条件,条件符合时跳出整个嵌套循环体是常见的程序逻辑.在Javascript中有哪些跳出的方法呢?楼主简单整理了一下. 一. 使用多个break语句跳出 var breaked ...

  7. javascript中的12种循环遍历方法1

    1:for循环 let arr = [1,2,3]; for(let i =0;i<arr.length;i++){ console.log(i,arr[i]) } //for循环是js中最常用 ...

  8. javascript中的12种循环遍历方法

    1.for (自定义条件) 循环 let arr = [1,2,3]; for(let i =0;i<arr.length;i++){ console.log(i,arr[i]) } 2.for ...

  9. Javascript中while和do-while循环用法详解

    while循环 while 语句与 if 语句相似,都有条件来控制语句(或语句块)的执行,其语言结构基本相同:while(conditions){    statements;} while 语句与 ...

随机推荐

  1. C#保存Base64格式图片

    .前端页面代码 /** * 通过图片本地路径获取图片真实大小,并进行压缩 */ function getLocalRealSize(path, callback) { var img = new Im ...

  2. java多条件不定条件查询

    网站或各类管理系统都会用到搜索,会用到一个或多个不确定条件搜索,单条件搜索比较简单,有时候会有多个条件共同查询,如果系统中已经提供了相关的方法供你使用最好,像我做这老系统改版,需要添加搜索,就要自己写 ...

  3. 关于loadrunner录制不跳转到IE

    我是一个新手,对于这个问题,我已经愁了两周左右,因为是自学,一直没人教,靠自己百度也一直解决不了. 今天,我总算解决了这个问题. 我之前是ie8,根据网上说的启动IE----工具---Internet ...

  4. IIS7.5支持html页面包含(include)html页面

    前提条件: ServerSideIncludeModule的安装: 在安装iis的时候选择上该服务(“在服务端包含文件”,选项)即可,如下: 1:处理映射程序 添加模块映射 请求路径 *.html 模 ...

  5. LVS三种模式配置及优点缺点比较

    目录: LVS三种模式配置 LVS 三种工作模式的优缺点比较 LVS三种模式配置 LVS三种(LVS-DR,LVS-NAT,LVS-TUN)模式的简要配置 LVS是什么: http://www.lin ...

  6. office2003-2007 绿色版 出错 文件丢失(未解决)

    - 这个版本是我大学时候(2012)年一直用到现在的版本:目录结构如下: 原来一直在32位系统中使用,没有出错过; - 刚装的两台电脑系统分别为 Win7Pro 和 Win10Pro ,都是64位的: ...

  7. 【03_136】Single Number

    感谢:http://www.cnblogs.com/changchengxiao/p/3413294.html Single Number Total Accepted: 103007 Total S ...

  8. Poj-1157-LITTLE SHOP OF FLOWERS

    题意为从每行取一瓶花,每瓶花都有自己的审美价值 第 i+1 行取的花位于第 i 行的右下方 求最大审美价值 dp[i][j]:取到第 i 行,第 j 列时所获得的最大审美价值 动态转移方程:dp[i] ...

  9. nginx安装启动

    参考:http://network.51cto.com/art/201005/198198_4.htm 下载nginx tar.gz安装包下载pcre tar.gz安装包 安装pcretar zxvf ...

  10. RHEL5.8使用yum安装X Window System

    硬件配置:4C+16GB 操作系统:Red Hat Enterprise Linux Server release 5.8 (Tikanga) 服务器中使用的是RHEL5.8操作系统,只安装了基本的功 ...