Array.fill(Array) Creates Copies by Reference
When using Array.fill to create multidimensional arrays, it's important to be aware that the inner arrays are initially copies by reference. This means that any modification to one inner array will be reflected in all others referencing the same Array object.
For example:
let m = Array(6).fill(Array(12).fill(0)); m[0][0] = 1; console.log(m[1][0]); // Outputs 1 instead of 0
To address this issue, you can use Array.from() instead of Array.fill():
let m = Array.from({length: 6}, e => Array(12).fill(0)); 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
Array.from() creates a copy of the iterable object (in this case, an object with a length property and a mapping function that returns a new array). This ensures that each inner array is independent and any modifications to one will not affect the others.
The above is the detailed content of Why Does Array.fill(Array) Create Copies by Reference in Multidimensional Arrays?. For more information, please follow other related articles on the PHP Chinese website!