Home > Web Front-end > JS Tutorial > How to Avoid Reference Passing When Using Array.prototype.fill() with Objects?

How to Avoid Reference Passing When Using Array.prototype.fill() with Objects?

Linda Hamilton
Release: 2025-01-01 13:17:10
Original
192 people have browsed it

How to Avoid Reference Passing When Using Array.prototype.fill() with Objects?

Passing Objects to Array.prototype.fill() by Reference

When initializing an array with a fixed length using the fill() method, assigning an object as the value results in all array elements referencing the same object rather than creating new instances. This can lead to unintended behavior when modifying array elements.

Example:

var arr = new Array(2).fill({});

console.log(arr[0] === arr[1]); // true
arr[0].test = 'string';
console.log(arr[1].test); // 'string'
Copy after login

Avoiding Reference Passing:

To create an array of objects with each element being a distinct instance, avoid using fill() directly with an object. Instead, follow these alternative approaches:

Map Function:

Fill the array with a placeholder value (e.g., undefined) and use map() to transform each element into a new object:

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

Object Factory Function:

Use a function that returns a new object to fill the array:

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

By employing these techniques, you can ensure that each element in the array is an individual object, avoiding unintended reference passing and maintaining object isolation.

The above is the detailed content of How to Avoid Reference Passing When Using Array.prototype.fill() with Objects?. 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