如何打破 underscore.js 中的 _.each 函数

发布于 2024-12-25 08:03:30 字数 247 浏览 2 评论 0原文

我正在寻找一种方法来停止 underscore.js _.each() 方法的迭代,但找不到解决方案。如果您返回 false,jQuery .each() 可能会中断。

有没有办法停止在each()下划线?

_([1,2,3]).each(function(v){
    if (v==2) return /*what?*/;
})

I'm looking for a way to stop iterations of underscore.js _.each() method, but can't find the solution. jQuery .each() can break if you do return false.

Is there a way to stop underscore each()?

_([1,2,3]).each(function(v){
    if (v==2) return /*what?*/;
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

安静被遗忘 2025-01-01 08:03:30

您无法脱离 each 方法 - 它模拟本机 forEach 方法的行为,并且本机 forEach 不提供转义循环(除了抛出异常)。

但是,我们并没有失去所有希望!您可以使用 Array.every 方法。 :)

从该链接:

every 对数组中存在的每个元素执行一次提供的 callback 函数,直到找到 callback 返回 false 值的元素。如果找到这样的元素,every 方法会立即返回 false。

换句话说,你可以做一些像这样复杂的事情(链接到 JSFiddle):

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

这会提醒 13,然后“break”出循环。

您正在使用 underscore.js,因此您会很高兴得知它确实提供了 every 方法 - 他们称之为 every,但正如该链接提到的,它们还提供了一个名为 all 的别名。

You can't break from the each method—it emulates the native forEach method's behavior, and the native forEach doesn't provide to escape the loop (other than throwing an exception).

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

From that link:

every executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method 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 1 through 3, and then "break" out of the loop.

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

翻了热茶 2025-01-01 08:03:30

更新:

_.find 会更好,因为它在找到元素时会跳出循环:

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){ 
              count = count +1;
              if(arrEl.id === 1 ){
                  return arrEl;
              }
            });

console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1

** 旧 **

如果您想有条件地跳出循环,请使用 _.filter api 而不是 _.each。这是一个代码片段

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){ 
                  if(arrEl.id === 1 ){
                      return arrEl;
                  }
                });
console.log(filteredEl);
//output: {id:1,text:"foo"}

Update:

_.find would be better as it breaks out of the loop when the element is found:

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){ 
              count = count +1;
              if(arrEl.id === 1 ){
                  return arrEl;
              }
            });

console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1

** Old **

If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){ 
                  if(arrEl.id === 1 ){
                      return arrEl;
                  }
                });
console.log(filteredEl);
//output: {id:1,text:"foo"}
笨笨の傻瓜 2025-01-01 08:03:30

您可以查看 _.some 而不是 _.each
一旦谓词为 true,_.some 就会停止遍历列表。
结果可以存储在外部变量中。

_.some([1, 2, 3], function(v) {
    if (v == 2) return true;
})

请参阅http://underscorejs.org/#some

You can have a look to _.some instead of _.each.
_.some stops traversing the list once a predicate is true.
Result(s) can be stored in an external variable.

_.some([1, 2, 3], function(v) {
    if (v == 2) return true;
})

See http://underscorejs.org/#some

蓝天 2025-01-01 08:03:30
_([1,2,3]).find(function(v){
    return v if (v==2);
})
_([1,2,3]).find(function(v){
    return v if (v==2);
})
春花秋月 2025-01-01 08:03:30

也许你想要Underscore的any()或find(),它们会在满足条件时停止处理。

Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.

会傲 2025-01-01 08:03:30

就像其他答案一样,这是不可能的。
这是关于下划线断路器的评论 下划线问题 #21

Like the other answers, it's impossible.
Here is the comment about breaker in underscore underscore issue #21

醉南桥 2025-01-01 08:03:30

您不能在下划线中中断 forEach,因为它模拟 EcmaScript 5 本机行为。

You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.

泼猴你往哪里跑 2025-01-01 08:03:30

我相信如果您的数组实际上是一个对象,您可以使用空对象返回。

_.({1,2,3,4,5}).each(function(v){  
  if(v===3) return {}; 
});

I believe if your array was actually an object you could return using an empty object.

_.({1,2,3,4,5}).each(function(v){  
  if(v===3) return {}; 
});
﹏半生如梦愿梦如真 2025-01-01 08:03:30

值得注意的是,each 循环不能脱离 —
中断,使用 _.find 代替。

http://underscorejs.org/#each

It's also good to note that an each loop cannot be broken out of — to
break, use _.find instead.

http://underscorejs.org/#each

┈┾☆殇 2025-01-01 08:03:30

更新:

您实际上可以通过在内部抛出错误并在外部捕获它来“中断”:如下所示:

try{
  _([1,2,3]).each(function(v){
    if (v==2) throw new Error('break');
  });
}catch(e){
  if(e.message === 'break'){
    //break successful
  }
}

这显然对您的代码在循环中触发的任何其他异常有一些影响,因此请谨慎使用!

Update:

You can actually "break" by throwing an error inside and catching it outside: something like this:

try{
  _([1,2,3]).each(function(v){
    if (v==2) throw new Error('break');
  });
}catch(e){
  if(e.message === 'break'){
    //break successful
  }
}

This obviously has some implications regarding any other exceptions that your code trigger in the loop, so use with caution!

还给你自由 2025-01-01 08:03:30

在我的案例中起作用

var arr2 = _.filter(arr, function(item){
    if ( item == 3 ) return item;
});

worked in my case

var arr2 = _.filter(arr, function(item){
    if ( item == 3 ) return item;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文