Home >Web Front-end >JS Tutorial >Why Does JavaScript\'s `Array.fill()` Create Shared References Instead of Copies, and How Can `Array.from()` Fix This?

Why Does JavaScript\'s `Array.fill()` Create Shared References Instead of Copies, and How Can `Array.from()` Fix This?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-28 14:51:11573browse

Why Does JavaScript's `Array.fill()` Create Shared References Instead of Copies, and How Can `Array.from()` Fix This?

Array.fill() Creates Hidden Copy by References, Not by Value

When utilizing Array.fill in JavaScript, one may encounter a situation where multiple inner arrays in a matrix reference the same underlying array object. This can lead to unexpected behavior when attempting to modify individual elements.

The Problem

For instance, consider the following code snippet:

let m = Array(6).fill(Array(12).fill(0));

This code aims to create a 6x12 matrix, where each element is initialized to 0. However, there's a subtle issue:

m[0][0] = 1;
console.log(m[1][0]); // Outputs 1 instead of 0

After setting m[0][0] to 1, we would expect m[1][0] to remain 0. However, the console displays 1. This is due to the fact that all inner arrays actually reference the same underlying array object.

The Solution: Array.from() to the Rescue

To resolve this issue and achieve a true copy-by-value, one can employ Array.from():

let m = Array.from({length: 6}, e => Array(12).fill(0));

This approach creates a new array for each element in the outer array, ensuring that all inner arrays are distinct objects. As a result, modifying one element will not affect the others:

m[0][0] = 1;
console.log(m[0][0]); // Expecting 1
console.log(m[0][1]); // Expecting 0
console.log(m[1][0]); // Expecting 0

The above is the detailed content of Why Does JavaScript\'s `Array.fill()` Create Shared References Instead of Copies, and How Can `Array.from()` Fix This?. 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