Home >Web Front-end >JS Tutorial >How Can I Ensure Unique Objects When Using Array.prototype.fill()?
Array.prototype.fill(): Passing Objects as References
The Array.prototype.fill() method is a convenient utility for initializing an array with a specified value. However, when filling an array with objects, the objects are passed as references rather than creating new instances. This behavior raises the question of whether there is a way to ensure that each element of the array is a unique object.
Consider the following example:
var arr = new Array(2).fill({}); console.log(arr[0] === arr[1]); // true
In this example, two objects are created and passed as references to arr[0] and arr[1]. Modifying one element of the array will affect the other, as they are the same object:
arr[0].test = 'string'; console.log(arr[1].test); // 'string'
To create a new object for each element of an array using Array.prototype.fill(), you can follow these steps:
var arr = new Array(2).fill().map(u => ({}));
This approach ensures that each element of the array is a distinct object, isolated from the others:
arr[0].test = 'string'; console.log(arr[1].test); // undefined
The above is the detailed content of How Can I Ensure Unique Objects When Using Array.prototype.fill()?. For more information, please follow other related articles on the PHP Chinese website!