Passing Objects to Array.prototype.fill() by Reference
When initializing an array with a fixed length using the fill() method, assigning an object as the value results in all array elements referencing the same object rather than creating new instances. This can lead to unintended behavior when modifying array elements.
Example:
var arr = new Array(2).fill({}); console.log(arr[0] === arr[1]); // true arr[0].test = 'string'; console.log(arr[1].test); // 'string'
Avoiding Reference Passing:
To create an array of objects with each element being a distinct instance, avoid using fill() directly with an object. Instead, follow these alternative approaches:
Map Function:
Fill the array with a placeholder value (e.g., undefined) and use map() to transform each element into a new object:
var arr = new Array(2).fill().map(u => ({}));
Object Factory Function:
Use a function that returns a new object to fill the array:
var arr = new Array(2).fill().map(Object);
By employing these techniques, you can ensure that each element in the array is an individual object, avoiding unintended reference passing and maintaining object isolation.
The above is the detailed content of How to Avoid Reference Passing When Using Array.prototype.fill() with Objects?. For more information, please follow other related articles on the PHP Chinese website!