Initializing and filling multi dimension array in javascript

后端 未结 2 1005
有刺的猬
有刺的猬 2021-01-18 12:23

How do we initialize and create new multi dimension array?

Let\'s imagine if I want to initialize a 4x4 multi dimension array and fill it with 0\'s

Ideally,

相关标签:
2条回答
  • 2021-01-18 12:47

    To get an independent filled array, you could use Array.from and map a new array with mapped values.

    var array = Array.from({ length: 4 }, _ => Array.from({ length: 4 }, _ => 4));
    
    array[0][0] = 0;
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
  • 2021-01-18 13:10

    @NinaScholz' answer is much better—as always—but I finished writing this before seeing that answer so have decided to post anyway.

    Similar idea but without the use of Array.from. It creates a new array at the specified length, fills it with 0's so that it can be iterated, iterates it to replace 0's with a new array of the specified length filled with the specified value.

        
    const buildMatrix = (l, h, v) => Array(l).fill(0).map(_ => Array(h).fill(v));
    const matrix = buildMatrix(4,4,4);
    matrix[0][0] = 0;
    console.log(matrix);
    .as-console-wrapper { max-height: 100% !important; }

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