Home > Web Front-end > JS Tutorial > Does `Array.prototype.fill()` Create New Object Instances, or Share References?

Does `Array.prototype.fill()` Create New Object Instances, or Share References?

Mary-Kate Olsen
Release: 2024-12-19 11:56:09
Original
1014 people have browsed it

Does `Array.prototype.fill()` Create New Object Instances, or Share References?

Array.prototype.fill() with Objects: Reference Sharing, Not Instance Creation

When using Array.prototype.fill() with an object, it's important to note that it passes a reference to the same object instance instead of creating new instances for each element. This behavior is demonstrated by the following code:

var arr = new Array(2).fill({});
arr[0] === arr[1]; // true (they point to the same object)
arr[0].test = 'string';
arr[1].test === 'string'; // true (changes made to one object are reflected in the other)
Copy after login

To avoid this reference sharing and ensure that each element holds a unique object instance, the map() function can be used:

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

In these cases, map() creates new objects for each element, eliminating the reference sharing issue.

The above is the detailed content of Does `Array.prototype.fill()` Create New Object Instances, or Share References?. 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