使用下划线的惰性范围迭代

发布于 2024-12-06 14:37:35 字数 244 浏览 0 评论 0原文

我发现自己使用它来代替传统的 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 技术交流群。

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

发布评论

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

评论(4

撕心裂肺的伤痛 2024-12-13 14:37:35

请注意:

_.each(_.range(count), function(i){
  ...
});

相当于

_.times(count, function(i){
  ...
});

小就是美......

Just a note:

_.each(_.range(count), function(i){
  ...
});

is equivalent to

_.times(count, function(i){
  ...
});

small is beautiful...

二货你真萌 2024-12-13 14:37:35

考虑到 underscore.js 的来源,关于 range 的内容如下:

生成一个包含算术级数的整数数组

我怀疑是否有一种方法可以在不修改源的情况下进行惰性迭代。

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.

蘑菇王子 2024-12-13 14:37:35

如果您不介意亲自动手,请深入研究较旧但稳定且功能完整的 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.

北城孤痞 2024-12-13 14:37:35

自 ECMAScript 2025 以来,我们有一些 迭代器助手开箱即用的方法,所以我们可以这样做:

Array(10).keys().forEach(n => console.log(n));

尽管 Array 创建了一个 Array 实例,但它没有任何索引槽,因此它不会消耗任何与其获取的长度参数成线性关系的内存。 keys 方法返回一个生成器,而(较新的)forEach 方法位于该迭代器上(而不是数组上),从而提供了惰性行为。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文