短路 Array.forEach 就像调用 break [英] Short circuit Array.forEach like calling break

查看:30
本文介绍了短路 Array.forEach 就像调用 break的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[1,2,3].forEach(function(el) {
    if(el === 1) break;
});

我如何使用 JavaScript 中的新 forEach 方法来实现这一点?我试过 return;return false;break.break 崩溃,return 除了继续迭代什么都不做.

How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.

推荐答案

forEach 没有内置的 break 功能.要中断执行,您必须抛出某种异常.例如.

There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.

var BreakException = {};

try {
  [1, 2, 3].forEach(function(el) {
    console.log(el);
    if (el === 2) throw BreakException;
  });
} catch (e) {
  if (e !== BreakException) throw e;
}

JavaScript 异常并不是非常漂亮.如果您确实需要在其中 break 循环,则传统的 for 循环可能更合适.

JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.

改为使用 Array#some:

[1, 2, 3].some(function(el) {
  console.log(el);
  return el === 2;
});

这是有效的,因为只要以数组顺序执行的任何回调返回 truesome 就会返回 true,从而短路执行其余部分.

This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.

some,它的逆every(将在 return false 处停止)和 forEach 都是 ECMAScript 第五版方法,需要添加到 Array.prototype 在缺少它们的浏览器上.

some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.

这篇关于短路 Array.forEach 就像调用 break的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆