Break out of an _.each loop

馋奶兔 提交于 2019-12-04 11:15:57

I don't think you can, so you will just have to wrap the contents of the function in i < 2 or use return. It may make more sense to use .some or .every.

EDIT:

//pseudo break
_.each(obj, function (v, i) {
    if (i <= 2) {
        // some code here
        // ...
    }
});

The issue with the above is of course that it has to do the entire loop, but that is simply a weakness of underscore's each.

You could use .every, though (either native array method or underscore's method):

_.every(obj, function (v, i) {
    // some code here
    // ...
    return i <= 2;
});

For now you cannot break an each loop. It is being discussed here: https://github.com/documentcloud/underscore/issues/596

Maybe on a future version.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!