Home > Web Front-end > JS Tutorial > Why Does Array.fill(Array) Create Copies by Reference in Multidimensional Arrays?

Why Does Array.fill(Array) Create Copies by Reference in Multidimensional Arrays?

Barbara Streisand
Release: 2024-11-29 09:30:11
Original
877 people have browsed it

Why Does Array.fill(Array) Create Copies by Reference in Multidimensional Arrays?

Array.fill(Array) Creates Copies by Reference

When using Array.fill to create multidimensional arrays, it's important to be aware that the inner arrays are initially copies by reference. This means that any modification to one inner array will be reflected in all others referencing the same Array object.

For example:

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

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

To address this issue, you can use Array.from() instead of Array.fill():

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

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

Array.from() creates a copy of the iterable object (in this case, an object with a length property and a mapping function that returns a new array). This ensures that each inner array is independent and any modifications to one will not affect the others.

The above is the detailed content of Why Does Array.fill(Array) Create Copies by Reference in Multidimensional Arrays?. 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