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?
The already mentioned ES 6 fill method takes care of this nicely. Most modern desktop browsers already support the required Array prototype methods as of today (Chromium, FF, Edge and Safari) [1]. You can look up details on MDN. A simple usage example is
Given the current browser support you should be cautious to use this unless you are sure your audience uses modern Desktop browsers.
I have nothing against:
suggested by Zertosh, but in a new ES6 array extensions allow you to do this natively with
fill
method. Now IE edge, Chrome and FF supports it, but check the compatibility tablenew Array(3).fill(0)
will give you[0, 0, 0]
. You can fill the array with any value likenew Array(5).fill('abc')
(even objects and other arrays).On top of that you can modify previous arrays with fill:
which gives you:
[1, 2, 3, 9, 9, 6]
Note that
while
is usually more efficient thanfor-in
,forEach
, etc.Although this is an old thread, I wanted to add my 2 cents to it. Not sure how slow/fast this is, but it's a quick one liner. Here is what I do:
If I want to pre-fill with a number:
If I want to pre-fill with a string:
Other answers have suggested:
but if you want 0 (the number) and not "0" (zero inside a string), you can do:
Using lodash or underscore
Or if you have an array existing and you want an array of the same length
The fastest way to do that is with forEach =)
(we keep backward compatibility for IE < 9)