forEach中return有效果吗?如何中断forEach循环?

在forEach中用return不会返回,函数会继续执行。

arr.forEach(callback[, thisArg]),callback会接收到三个参数:currentValue、index、array。

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

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

程序并不会中断执行。

JavaScript
Java
CoffeeScript
TypeScript

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

try {
  ary.forEach(function (el) {
    console.log(el);
    if (el === "CoffeeScript") throw BreakException;
  });
} catch (e) {
  if (e !== BreakException) throw e;
};

JavaScript
Java
CoffeeScript

重写forEach(也是借鉴第一种方法)

(function () {
  if (typeof StopIteration == "undefined") {
    StopIteration = new Error("StopIteration");
  }

  var oldForEach = Array.prototype.forEach;

  if (oldForEach) {
    Array.prototype.forEach = function () {
      try {
        oldForEach.apply(this, [].slice.call(arguments, 0));
      }
      catch (e) {
        if (e !== StopIteration) {
          throw e;
        }
      }
    };
  }
})();


ary.forEach(function (val) {
  console.log(val);
  if (val === "CoffeeScript")
    throw StopIteration;
});

官方推荐方法(替换方法):用every和some替代forEach函数。every在碰到return false的时候,中止循环。some在碰到return true的时候,中止循环

使用 some 函数

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

JavaScript
Java
CoffeeScript

使用 every 函数

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

JavaScript

使用 for…of 函数

for (let el of ary) {
  console.log(el);
  if (el === "CoffeeScript") {
    break;
  }
}

JavaScript
Java
CoffeeScript

如何实现一个 forEach ?

其实本质上还是使用了 for 循环。使用 call,改变 callback。

Array.prototype.forEach = function (callback) {
  console.log('this is my forEach')
  if (this === undefined) {
    throw new TypeError('this is null or not undefined')
  }
  if (typeof callback !== "function") {
    throw new TypeError(callback + 'is not a function')
  }
  // this:当前调用的对象
  const o = Object(this);
  // len: 长度
  const len = o.length >>> 0
  for (let i = 0; i < len; i++) {
    if (i in o) {
      callback.call(null, o[i], i);
    }
  }
}

参考文章:
https://cloud.tencent.com/developer/article/1365491

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值