admin管理员组文章数量:1357387
I've caught myself using this in place of a traditional for loop:
_.each(_.range(count), function(i){
...
});
The disadvantage being creating an unnecessary array of size count.
Still, i prefer the semantics of, for example, .each(.range(10,0,-1), ...); when iterating backwards.
Is there any way to do a lazy iteration over range, as with pythons xrange?
I've caught myself using this in place of a traditional for loop:
_.each(_.range(count), function(i){
...
});
The disadvantage being creating an unnecessary array of size count.
Still, i prefer the semantics of, for example, .each(.range(10,0,-1), ...); when iterating backwards.
Is there any way to do a lazy iteration over range, as with pythons xrange?
Share Improve this question edited Nov 29, 2024 at 11:04 DarkBee 15.5k8 gold badges72 silver badges117 bronze badges asked Sep 26, 2011 at 5:03 v_yv_y 3252 silver badges9 bronze badges 2- 1 Any reason not to use a simple for loop? – Dogbert Commented Sep 26, 2011 at 5:11
- i find it easier to see what's going on with range(n,0,-1) – v_y Commented Sep 26, 2011 at 5:36
4 Answers
Reset to default 3Just a note:
_.each(_.range(count), function(i){
...
});
is equivalent to
_.times(count, function(i){
...
});
small is beautiful...
Considering the source of underscore.js says the following about range
:
Generate an integer Array containing an arithmetic progression
I doubt there is a way to do lazy iteration without modifying the source.
If you don't mind getting your hands dirty, dig into the sources of the older but stable and feature-plete MochiKit's Iter module. It tries to create something along the lines of Python's itertools.
Since ECMAScript 2025, we have a few iterator helper methods out of the box, and so we can do:
Array(10).keys().forEach(n => console.log(n));
Even though Array
creates an Array instance, it does not have any index slots, so it does not consume any memory that is linear to the length argument it gets. The keys
method returns a generator, and the (newer) forEach
method is on that iterator (not on the array), giving the lazy behaviour.
本文标签: javascriptLazy range iteration using underscoreStack Overflow
版权声明:本文标题:javascript - Lazy range iteration using underscore - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744064192a2584684.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论