Home >Web Front-end >JS Tutorial >Why Does Array.fill() Create Shared References in Two-Dimensional Arrays?

Why Does Array.fill() Create Shared References in Two-Dimensional Arrays?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 11:18:09995browse

Why Does Array.fill() Create Shared References in Two-Dimensional Arrays?

Array.fill() Copies References, Not Values

When attempting to initialize a two-dimensional matrix with Array.fill(), you may encounter an issue where the inner arrays share references, causing unexpected results.

To address this problem, you can utilize Array.from():

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

m[0][0] = 1;
console.log(m[0][0]); // Outputs 1, as expected
console.log(m[1][0]); // Outputs 0, as intended

This approach creates copy-by-value inner arrays, ensuring that modifications to one array do not affect the others. Each inner array is a distinct object, providing the desired independence.

The above is the detailed content of Why Does Array.fill() Create Shared References in Two-Dimensional Arrays?. 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