栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/606026.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号