Home > Web Front-end > JS Tutorial > Why Does Array.fill(Array) Create Copies by Reference in JavaScript, and How Can This Be Avoided?

Why Does Array.fill(Array) Create Copies by Reference in JavaScript, and How Can This Be Avoided?

DDD
Release: 2024-11-28 15:38:12
Original
452 people have browsed it

Why Does Array.fill(Array) Create Copies by Reference in JavaScript, and How Can This Be Avoided?

Array.fill(Array) Creates Copies by Reference in JavaScript

Array.fill() is a useful method for populating an array with a specific value. However, when used to create arrays within arrays, it creates a referencing issue.

Consider the following example:

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

This code attempts to create a 6x12 matrix, where each element is 0. However, the inner arrays all reference the same array object.

To illustrate:

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

Instead of 0, the code above outputs 1 because changes to one element affect all other elements referencing the same array object.

To create copies by value, one solution is to use Array.from() instead:

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

This syntax creates a new array for each element in the outer array, resulting in true copy-by-value behavior.

The above is the detailed content of Why Does Array.fill(Array) Create Copies by Reference in JavaScript, and How Can This Be Avoided?. 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