Whats The Difference Between Array.fill And A For Loop To Create Array
I'm creating a dungeon crawler game using React.js and I was initializing the board using Array.fill(0). but when I set an element inside the 2d array it sets the entire Array (col
Solution 1:
You are using Array#fill
correctly. Array#fill
populates the array cells with the same value:
- The sub array is created - Array(col).fill(0)
- All row arrays are filled with the array reference - Array(row).fill(Array(col).fill(0))
To prevent that, you can use other methods of array creation, that create instead of clone the value. For example Array#from
:
const row = 10;
const col = 5;
const result = Array.from({ length: row }, () => new Array(col).fill(0));
result[0][2] = 5
console.log(result);
Solution 2:
You can fill 2D array with a help of Array.fill in a such way:
let arr = Array(5).fill(0).map(x => Array(5).fill(0))
Post a Comment for "Whats The Difference Between Array.fill And A For Loop To Create Array"