Whats the difference between Array.fill and a for loop to create Array

后端 未结 2 980
忘掉有多难
忘掉有多难 2020-12-07 00:11

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 Ar

相关标签:
2条回答
  • 2020-12-07 00:35

    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))
    
    0 讨论(0)
  • 2020-12-07 00:58

    You are using Array#fill correctly. Array#fill populates the array cells with the same value:

    1. The sub array is created - Array(col).fill(0)
    2. 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);

    0 讨论(0)
提交回复
热议问题