Home >Web Front-end >JS Tutorial >How Can I Ensure Unique Objects When Using Array.prototype.fill()?

How Can I Ensure Unique Objects When Using Array.prototype.fill()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 16:50:20262browse

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:

  1. Fill the array with any arbitrary value (e.g., undefined) using the fill() method.
  2. Use the map() method to create a new array with new instances of the desired object type:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn