Array.fill() is a useful method for populating an array with a specific value. However, when used to create arrays within arrays, it creates a referencing issue.
Consider the following example:
let m = Array(6).fill(Array(12).fill(0));
This code attempts to create a 6x12 matrix, where each element is 0. However, the inner arrays all reference the same array object.
To illustrate:
m[0][0] = 1; console.log(m[1][0]); // Outputs 1 instead of 0
Instead of 0, the code above outputs 1 because changes to one element affect all other elements referencing the same array object.
To create copies by value, one solution is to use Array.from() instead:
let m = Array.from({length: 6}, e => Array(12).fill(0));
This syntax creates a new array for each element in the outer array, resulting in true copy-by-value behavior.
The above is the detailed content of Why Does Array.fill(Array) Create Copies by Reference in JavaScript, and How Can This Be Avoided?. For more information, please follow other related articles on the PHP Chinese website!