如何打破_ Underscore.js。在每个函数

2018-03-07

Dan AtkinsonDmitry_F提出了一个问题:how to break the _.each function in underscore.js,或许与您遇到的问题类似。

回答者wil93aeskr给出了该问题的处理方式:

You can't break from the eachmethod—it emulates the native forEachmethod's behavior, and the native forEachdoesn't provide to escape the loop (other than throwing an exception).

However, all hope is not lost!You can use the Array.everymethod. :)

From that link:

everyexecutes the provided callbackfunction once for each element present in the array until it finds one where callbackreturns a false value. If such an element is found, the everymethod immediately returns false.

In other words, you could do something convoluted like this (link to JSFiddle):

[1, 2, 3, 4].every(function(n) {
    alert(n);
    return n !== 3;
});

This will alert 1through 3, and then "break" out of the loop.

You're using underscore.js, so you'll be pleased to learn that it doesprovide an everymethod—they call it every, but as that link mentions, they also provide an alias called all.

希望本文对你有帮助,欢迎支持JavaScript中文网

原文链接:stackoverflow.com

上一篇:如何自动重新加载我正在开发的Chrome扩展?
下一篇:如何在循环中创建对象文本数组?
相关教程
关注微信

扫码加入 JavaScript 社区

相关文章

首次访问,需要验证
微信扫码,关注即可
(仅需验证一次)

欢迎加入 JavaScript 社区

号内回复关键字:

回到顶部