Array.range() (was: Suggestion: Array.prototype.repeat)

Michael A. Smith michael at smith-li.com
Tue Jan 3 10:31:36 PST 2012


When I first started learning JavaScript I didn't understand how

new Array(n);

worked, in that it creates an empty array with a length of n. What I
had expected was an array with n values (even if it wasn't
well-defined what those values should be). So of course my attempt to
create an array of random numbers:

var rands = (new Array(6)).map(function () { return
Math.floor(Math.random() * (1001)) }; );

fell flat. This is one case where the earlier Array.prototype.repeat
proposal had merit. Either way I think the Array.prototype.range
suggestion is useful, but I wish it could generate an array with
arbitrary values. Maybe we could create a shortcut syntax instead of
requiring .map if the *value* parameter in Adam's proposal could
alternatively be a callback? (Is it safe to assume nobody wants to use
range to create an array of functions? Maybe not, but it would surely
be useful.)

Michael A. Smith
Web Developer
True Action Network, an eBay Company


On Tue, Jan 3, 2012 at 1:12 PM, Rick Waldron <waldron.rick at gmail.com> wrote:
>
>
> On Tue, Jan 3, 2012 at 12:50 PM, Sean Eagan <seaneagan1 at gmail.com> wrote:
>>
>> I think step should be > 0, and step towards end:
>>
>> Array.range({start: 5, end: 0, step: 2}) -> 5, 3, 1
>
>
> This would be an unfortunate limitation, considering real world impl's allow
> negative numbers...
> http://documentcloud.github.com/underscore/#range
>
>>
>>
>> On Tue, Jan 3, 2012 at 11:42 AM, Axel Rauschmayer <axel at rauschma.de>
>> wrote:
>> > I think it's fairly common for range implementations to provide an
>> > optional
>> > `step` parameter
>> >
>> >
>> > Good point. Maybe all of these parameters should be options:
>> >
>> > Array.range() -> 0, 1, 2, 3, ...
>> > Array.range({ start: 3 }) -> 3, 4, 5, 6, ...
>> > Array.range({ end: 5 }) -> 0, 1, 2, 3, 4
>> > Array.range({ step: 3 }) -> 0, 3, 6, 9, ...
>> > Array.range({ start: -2, step: -1 }) -> -2, -3, -4, -5, ...
>> > etc.
>> >
>> > The defaults of start and end and the comparison operator depend on the
>> > sign
>> > of step.
>> >
>> > --
>> > Dr. Axel Rauschmayer
>> > axel at rauschma.de
>> >
>> > home: rauschma.de
>> > twitter: twitter.com/rauschma
>> > blog: 2ality.com
>> >
>> >
>> >
>> >
>> > _______________________________________________
>> > es-discuss mailing list
>> > es-discuss at mozilla.org
>> > https://mail.mozilla.org/listinfo/es-discuss
>> >
>>
>>
>>
>> --
>> Sean Eagan
>
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


More information about the es-discuss mailing list