Array method ranges

Peter van der Zee ecma at qfox.nl
Thu Jan 24 03:06:23 PST 2013


What about adding specific range arguments to the es5 array methods
(forEach, map, etc)? Currently the start (inclusive) and stop
(exclusive) is always 0 ... length, but what if you only want to map
over a sub range of the array? Or maybe I want to traverse the array
in reverse? I'd either have to slice it or .reverse it, neither are
something I would want. So I fall back to `for` or `while` loops.

As for the context parameter, I believe undefined won't change the
context opposed to omitting it, right?

arr.forEach(function(){ ...});
// same as
arr.forEach(function(){ ...}, undefined, 0, arr.length);

arr.slice(10,10).forEach...
arr.slice(80,20).reverse().forEach...
=>
arr.forEach(function(){ ...}, undefined, 10, 20);
arr.forEach(function(){ ...}, undefined, 100, 80); // run from 100 to
80, backwards

Negative numbers could behave the same as in slice (offsets from the
last item, rather than the first).

arr.forEach(function(){ ...}, undefined, -20); // run from length-20 to length
arr.forEach(function(){ ...}, undefined, -20, -10); // run from
length-20 to length-10 (so, forward)
arr.forEach(function(){ ...}, undefined, -20, -30); // run from
length-20 to length-30 (so, backwards)

Of course, it would still skip the holes in sparse arrays.

- peter


More information about the es-discuss mailing list