Home > Web Front-end > JS Tutorial > Why Does Array.prototype.fill() Create Shared Object References, and How Can I Avoid It?

Why Does Array.prototype.fill() Create Shared Object References, and How Can I Avoid It?

DDD
Release: 2024-12-18 17:46:14
Original
678 people have browsed it

Why Does Array.prototype.fill() Create Shared Object References, and How Can I Avoid It?

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 => ({}));
Copy after login

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);
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template