Creating a filled array with a given length?

Jussi Kalliokoski jussi.kalliokoski at gmail.com
Thu Dec 13 01:14:42 PST 2012


On Wed, Dec 12, 2012 at 6:08 PM, Rick Waldron <waldron.rick at gmail.com>wrote:

>
>
>
> On Wed, Dec 12, 2012 at 1:59 AM, Axel Rauschmayer <axel at rauschma.de>wrote:
>
>> I would still love to have something like that in ES6 (loosely similar to
>> String.prototype.repeat). Once you have that, you can e.g. use
>> Array.prototype.map to do more things.
>>
>> Two possibilities:
>> - Array.repeat(undefined, 3) -> [ undefined, undefined, undefined ]
>> - [ undefined ].repeat(3) -> [ undefined, undefined, undefined ]
>>
>> The same array could be created like this, but that seems too much work
>> for a relatively common operation.
>>
>> 'x'.repeat(3).split('').map(=> undefined)
>>
>
> Array Comprehensions!
>
> This is probably wrong, so treat it more like an idea and less like a
> matter of fact:
>
> [ undefined for x of new Array(3) ].map( v => ... );
>
> [ undefined for x of [0,0,0] ].map( v => ... );
>

This should work, too (at least it works in Firefox, if you use a normal
function):

var powersOfTwo = [ ...Array(8) ].map( (v, i) => 1 << i )

Cheers,
Jussi


> Rick
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20121213/b7899bfc/attachment.html>


More information about the es-discuss mailing list