Array.prototype.fill() Referral Instead of Creating New Instance
When attempting to initialize an array using Array.prototype.fill(), the behavior can be unexpected when the fill value is an object. In this case, the references to the same object are stored in each element of the array, leading to unintended sharing of properties and behavior.
To address this, it is recommended to use alternative methods like map() to create new instances of objects for each element in the array. This can be achieved by first filling the array with an arbitrary value and then mapping each element to a new object:
var arr = new Array(2).fill().map(u => ({}));
Alternatively, you can use Object() as the mapper to create a new object for each array element:
var arr = new Array(2).fill().map(Object);
By employing these techniques, you can ensure that each element in the filled array is an independent object, eliminating potential issues related to shared references.
The above is the detailed content of Why Does Array.prototype.fill() Create Shared Object References, and How Can I Avoid It?. For more information, please follow other related articles on the PHP Chinese website!