Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

javascript - Array.forEach短路就像调用break(Short circuit Array.forEach like calling break)

[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

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

1 Reply

0 votes
by (71.8m points)

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 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...