ES6 allows us to fill an Array
with a certain value:
function emptyRow() {
return new Array(9).fill(0);
}
This function returns an Array
of length 9, filled with only zeros:
>> emptyRow()
<< Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
Now I want to generate an Array
that is filled with nine of those empty rows.
function emptyMatrix() {
return new Array(9).fill(emptyRow());
}
However, instead of fill
calling emptyRow()
nine times, it seems to call it once and fills the new Array
with nine references to the object created by emptyRow()
. Naturally, if I change a value within any of those sub-arrays, the value is changed at the same index for all sub-arrays.
Is there a way to create a new object for each entry?