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!