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
Add a ment  | 

4 Answers 4

Reset to default 3

Just 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