使用下划线的惰性范围迭代
我发现自己使用它来代替传统的 for 循环:
_.each(_.range(count), function(i){
...
});
缺点是创建了不必要的大小计数数组。
尽管如此,我还是更喜欢这样的语义,例如 .each(.range(10,0,-1), ...);当向后迭代时。
有没有办法像 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请注意:
相当于
小就是美......
Just a note:
is equivalent to
small is beautiful...
考虑到 underscore.js 的来源,关于
range
的内容如下:我怀疑是否有一种方法可以在不修改源的情况下进行惰性迭代。
Considering the source of underscore.js says the following about
range
:I doubt there is a way to do lazy iteration without modifying the source.
如果您不介意亲自动手,请深入研究较旧但稳定且功能完整的 MochiKit< 的源代码/a> 的 Iter 模块。它尝试创建一些类似于 Python 的 itertools 的东西。
If you don't mind getting your hands dirty, dig into the sources of the older but stable and feature-complete MochiKit's Iter module. It tries to create something along the lines of Python's itertools.
自 ECMAScript 2025 以来,我们有一些 迭代器助手开箱即用的方法,所以我们可以这样做:
尽管 Array 创建了一个 Array 实例,但它没有任何索引槽,因此它不会消耗任何与其获取的长度参数成线性关系的内存。
keys
方法返回一个生成器,而(较新的)forEach
方法位于该迭代器上(而不是数组上),从而提供了惰性行为。Since ECMAScript 2025, we have a few iterator helper methods out of the box, and so we can do:
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. Thekeys
method returns a generator, and the (newer)forEach
method is on that iterator (not on the array), giving the lazy behaviour.