Home >Web Front-end >JS Tutorial >Why Does JavaScript\'s `Array.fill()` Create Shared References Instead of Copies, and How Can `Array.from()` Fix This?
When utilizing Array.fill in JavaScript, one may encounter a situation where multiple inner arrays in a matrix reference the same underlying array object. This can lead to unexpected behavior when attempting to modify individual elements.
For instance, consider the following code snippet:
let m = Array(6).fill(Array(12).fill(0));
This code aims to create a 6x12 matrix, where each element is initialized to 0. However, there's a subtle issue:
m[0][0] = 1; console.log(m[1][0]); // Outputs 1 instead of 0
After setting m[0][0] to 1, we would expect m[1][0] to remain 0. However, the console displays 1. This is due to the fact that all inner arrays actually reference the same underlying array object.
To resolve this issue and achieve a true copy-by-value, one can employ Array.from():
let m = Array.from({length: 6}, e => Array(12).fill(0));
This approach creates a new array for each element in the outer array, ensuring that all inner arrays are distinct objects. As a result, modifying one element will not affect the others:
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
The above is the detailed content of Why Does JavaScript\'s `Array.fill()` Create Shared References Instead of Copies, and How Can `Array.from()` Fix This?. For more information, please follow other related articles on the PHP Chinese website!