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

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

Linda Hamilton
Release: 2024-11-30 09:50:15
Original
289 people have browsed it

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

Array.fill() in JavaScript: A Cautionary Tale of References vs. Values

Array.fill() is a JavaScript method used to fill an array with a specified value. However, it's important to understand that Array.fill() operates on references rather than values.

The Problem: Referencing vs. Values

Consider the following code:

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

Here, we create a 6x12 matrix using Array.fill(). However, when we set m0 to 1, m1 unexpectedly also becomes 1. This is because Array.fill() creates inner arrays that all reference the same Array object.

Expected Behavior: Values

Instead of referencing, we may want to copy values instead. In other words, changing m0 should not affect m1.

Solution: Using Array.from()

To force Array.fill() to copy values instead of references, we can use Array.from() as follows:

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

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

Array.from() ensures that each inner array is a distinct object, preventing unintended value sharing.

Conclusion

When using Array.fill(), be aware of the difference between references and values. For situations where you want to copy values rather than references, consider using Array.from() instead.

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