Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

(如何使用JavaScript中新的forEach方法做到这一点?)

I've tried return;

(我试过return;)

, return false;

(, return false;)

and break .

(和break 。)

break crashes and return does nothing but continue iteration.

(break崩溃, return并没有做任何事情,而是继续迭代。)

  ask by Scott Klarenbach translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
363 views
Welcome To Ask or Share your Answers For Others

1 Answer

There's no built-in ability to break in forEach .

(没有内置的能力可以break 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 exceptions aren't terribly pretty.

(JavaScript异常不是很漂亮。)

A traditional for loop might be more appropriate if you really need to break inside it.

(传统for ,如果你真的需要循环可能更适合break里面。)

Use Array#some (使用Array#some)

Instead, use Array#some :

(而是使用Array#some :)

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

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.

(之所以true是因为some以数组顺序执行的回调一旦返回true ,就会使true短路,从而使其余的执行短路。)

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.

(some ,其every相反(将在return false停止),以及forEach都是ECMAScript Fifth Edition方法,需要在缺少它们的浏览器上将它们添加到Array.prototype 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...