I want to create a two dimensionals array in JavaScript but I have some problems.
I don't understand why those two functions (which just create a two dimensionals Array with a defined size) don't work the same way.
function createArray(size) {
const arr = new Array(size);
for (let i = 0; i < size; ++i) {
arr[i] = new Array(size).fill(false);
}
return arr;
}
function createArrayFill(size) {
return new Array(size).fill(new Array(size).fill(false));
}
const array = createArray(3);
const arrayFill = createArrayFill(3);
console.log(array);
console.log(arrayFill);
array[1][1] = true;
arrayFill[1][1] = true;
console.log(array);
console.log(arrayFill);
Here is the output:
[ [ false, false, false ],
[ false, false, false ],
[ false, false, false ] ] // array OK
[ [ false, false, false ],
[ false, false, false ],
[ false, false, false ] ] // arrayFill OK
[ [ false, false, false ],
[ false, true, false ],
[ false, false, false ] ] // array OK
[ [ false, true, false ],
[ false, true, false ],
[ false, true, false ] ] // arrayFill FAIL
As we can see, both arrays are filled well: with only "false".
For both array we put the [1][1] to "true" but in the second one, it puts every cell of the second column to "true".
Do you know why?
I don't understand why both console.log display the same array but the same code don't do the same result.
(I am using node.js v7.1.0 to test the code)