Home >Web Front-end >JS Tutorial >Does `Array.prototype.fill()` Create New Object Instances, or Share References?
Array.prototype.fill() with Objects: Reference Sharing, Not Instance Creation
When using Array.prototype.fill() with an object, it's important to note that it passes a reference to the same object instance instead of creating new instances for each element. This behavior is demonstrated by the following code:
var arr = new Array(2).fill({}); arr[0] === arr[1]; // true (they point to the same object) arr[0].test = 'string'; arr[1].test === 'string'; // true (changes made to one object are reflected in the other)
To avoid this reference sharing and ensure that each element holds a unique object instance, the map() function can be used:
var arr = new Array(2).fill().map(u => ({})); var arr = new Array(2).fill().map(Object);
In these cases, map() creates new objects for each element, eliminating the reference sharing issue.
The above is the detailed content of Does `Array.prototype.fill()` Create New Object Instances, or Share References?. For more information, please follow other related articles on the PHP Chinese website!