Array method ranges

François REMY francois.remy.dev at outlook.com
Thu Jan 24 06:45:37 PST 2013


Good idea. However, I don't like the fact "arr.forEach(f,null,-1,0)" doesn't walk the array backwards properly. Not sure it's worth to have it built-in though.

----------------------------------------
> Date: Thu, 24 Jan 2013 12:06:23 +0100
> Subject: Array method ranges
> From: ecma at qfox.nl
> To: es-discuss at mozilla.org
>
> 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
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss 		 	   		  


More information about the es-discuss mailing list