如何短路Array.forEach就像调用突破? [英] How to short circuit Array.forEach like calling break?

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

问题描述

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

我怎样才能做到这一点使用新的的forEach 方法在JavaScript中?

How can I do this using the new forEach method in JavaScript?

推荐答案

有没有内置的能力的forEach $ C>。中断执行你将不得不抛出某种异常。例如:

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) {
        if(el === 1) throw BreakException;
    });
} catch(e) {
    if (e!==BreakException) throw e;
}

JavaScript异常并不十分pretty。如果你真的需要为里面传统的循环可能更合适。

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

相反,使用<一个href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/some\"><$c$c>Array#some:

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

这工作,因为部分收益真正只要任何回调,数组顺序执行的,返回真正,短路,其余的执行。

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.

部分,它的逆<一个href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/every\"><$c$c>every (这将停止在返回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就像调用突破?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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