Home > Web Front-end > JS Tutorial > Why Does `Array.prototype.fill()` Create Object References Instead of Copies?

Why Does `Array.prototype.fill()` Create Object References Instead of Copies?

Patricia Arquette
Release: 2024-12-13 07:55:12
Original
980 people have browsed it

Why Does `Array.prototype.fill()` Create Object References Instead of Copies?

Object Reference in Array.prototype.fill()

When using Array.prototype.fill() to initialize an array with objects, it's important to note that the method passes a reference to the same object rather than creating new instances for each element. This can lead to unexpected behavior when modifying properties of the objects after initialization.

Consider the following example:

var arr = new Array(2).fill({});
arr[0] === arr[1]; // true
arr[0].test = 'string';
arr[1].test === 'string'; // also true
Copy after login

In this example, two array elements are initialized with the same object reference. As a result, both arr[0] and arr[1] reference the same object. When the test property is set on arr[0], it is also automatically set on arr[1] due to the shared reference.

To avoid this issue, one can instead fill the array with any arbitrary value and then use map() to create new objects for each element:

var arr = new Array(2).fill(undefined).map(u => ({}));
var arr = new Array(2).fill().map(Object);
Copy after login

In these examples, the undefined or null value is initially used to fill the array. Subsequently, map() is used to create new objects for each element, effectively filling the array with distinct objects.

The above is the detailed content of Why Does `Array.prototype.fill()` Create Object References Instead of Copies?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template