Array().fill acts weirdly

// Option 1
function initialize() {
let matrix = new Array(3).fill(["-", "-", "-"]);
return matrix;
};
// Option 2
function initialize() {
let matrix = new Array();
for (; matrix.length < 3;) {
let row = ["-", "-", "-"];
matrix.push(row);
};
return matrix;
};
// Option 1
function initialize() {
let matrix = new Array(3).fill(["-", "-", "-"]);
return matrix;
};
// Option 2
function initialize() {
let matrix = new Array();
for (; matrix.length < 3;) {
let row = ["-", "-", "-"];
matrix.push(row);
};
return matrix;
};
If I do matrix[0][0] = "a" in option 1 matrix, it replaces entire 1st column with "a". But that's not the case for option 2, it only only replaces at the specified position.
5 Replies
ἔρως
ἔρως3mo ago
because you're filling the array with the same reference to the array you're not filling with 3 different copies of the same array this is the same as doing this:
let x = [1, 2, 3];
let y = [x, x, x];
let x = [1, 2, 3];
let y = [x, x, x];
oh, and the 2nd one is the equivalent of this:
let x = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
];
let x = [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
];
so, when you change the index on the first, you're actually changing the index on the same array for all
brr
brrOP3mo ago
with the same reference
brr
brrOP3mo ago
thanks
ἔρως
ἔρως3mo ago
you're welcome

Did you find this page helpful?