"Array.prototype.fill() uses objects to pass references instead of creating new instances"
P粉682987577
2023-08-23 09:15:17
<p>I was playing around a bit, trying to instantiate a new array of length <code>x</code>, where all elements of the array were initialized to the value <code>y</code>:< /p>
<pre class="brush:php;toolbar:false;">var arr = new Array(x).fill(y);</pre>
<p>This method works well if the value of <code>y</code> is not an <strong>object</strong>.
That is, if <code>y</code> is an object, then the following conditions are true: </p>
<pre class="brush:php;toolbar:false;">var arr = new Array(2).fill({});
arr[0] === arr[1]; //The result is true;
arr[0].test = 'string';
arr[1].test === 'string'; //The result is also true;</pre>
<p>Is there a way to declare that a new object should be created for each element when using the fill function? Or should I convert it to a loop? </p>
The accepted answer is great and works 90% of the time.
However, if you are making a high-performance JS application and are using large/huge arrays, Array.map(..) will create a lot of load in terms of memory and processor usage, Because it creates a copy of the array.
I recommend using the classic for loop:
I tested six alternatives and got the following results:
Array.map(), as above (11 times slower than the original! ):
for loop, best choice (fastest):
forEach (slower 6 times ):
[Updated on 2020-08-27] Ilias Karim proposed another method
Array.from (30 times slower! ) - Definitely worse in terms of performance, despite having the best syntax :(
[..Array(..)] (5 times slower!)
Array.push(..), ranked second in terms of performance (2x slower! )
PS: I tested on this fiddle.
You can first fill the array with any value (e.g.
undefined
) and then you can usemap
: