Object Reference in Array.prototype.fill()
When using Array.prototype.fill() to initialize an array with objects, it's important to note that the method passes a reference to the same object rather than creating new instances for each element. This can lead to unexpected behavior when modifying properties of the objects after initialization.
Consider the following example:
var arr = new Array(2).fill({}); arr[0] === arr[1]; // true arr[0].test = 'string'; arr[1].test === 'string'; // also true
In this example, two array elements are initialized with the same object reference. As a result, both arr[0] and arr[1] reference the same object. When the test property is set on arr[0], it is also automatically set on arr[1] due to the shared reference.
To avoid this issue, one can instead fill the array with any arbitrary value and then use map() to create new objects for each element:
var arr = new Array(2).fill(undefined).map(u => ({})); var arr = new Array(2).fill().map(Object);
In these examples, the undefined or null value is initially used to fill the array. Subsequently, map() is used to create new objects for each element, effectively filling the array with distinct objects.
The above is the detailed content of Why Does `Array.prototype.fill()` Create Object References Instead of Copies?. For more information, please follow other related articles on the PHP Chinese website!