What is the most efficient way to create an arbitrary length zero filled array in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Elegant way to fill an array with precomputed values
Here is another way to do it using ES6 that nobody has mentioned so far:
It works by passing a map function as the second parameter of
Array.from
.In the example above, the first parameter allocates an array of 3 positions filled with the value
undefined
and then the lambda function maps each one of them to the value0
.Although
Array(len).fill(0)
is shorter, it doesn't work if you need to fill the array by doing some computation first (I know the question didn't ask for it, but a lot of people end up here looking for this).For instance, if you need an array with 10 random numbers:
It's more concise (and elegant) than the equivalent:
This method can also be used to generate sequences of numbers by taking advantage of the index parameter provided in the callback:
Bonus answer: fill an array using String
repeat()
Since this answer is getting a good deal of attention, I also wanted to show this cool trick. Although not as useful as my main answer, will introduce the still not very known, but very useful String
repeat()
method. Here's the trick:Cool, huh?
repeat()
is a very useful method to create a string that is the repetition of the original string a certain number of times. After that,split()
creates an array for us, which is thenmap()
ped to the values we want. Breaking it down in steps:usage in expressions:
arr[i]*1;
EDIT: if
arr
supposed to be used in integer expressions, then please don't mind the char value of '0'. You just use it as follows:a = a * arr[i]
(assuminga
has integer value).It might be worth pointing out, that
Array.prototype.fill
had been added as part of the ECMAScript 6 (Harmony) proposal. I would rather go with the polyfill written below, before considering other options mentioned on the thread.What about
new Array(51).join('0').split('')
?ES6 introduces
Array.prototype.fill
. It can be used like this:Not sure if it's fast, but I like it because it's short and self-describing.
It's still not in IE (check compatibility), but there's a polyfill available.
using object notation
zero filled? like...
filled with 'undefined'...
obj notation with zeros
As a side note, if you modify Array's prototype, both
and
will have those prototype modifications
At any rate, I wouldn't be overly concerned with the efficiency or speed of this operation, there are plenty of other things that you will likely be doing that are far more wasteful and expensive than instanciating an array of arbitrary length containing zeros.