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
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
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!