Declare an empty two-dimensional array in Javascript?

后端 未结 18 1402
暖寄归人
暖寄归人 2020-11-29 21:45

I want to create a two dimensional array in Javascript where I\'m going to store coordinates (x,y). I don\'t know yet how many pairs of coordinates I will have because they

18条回答
  •  不知归路
    2020-11-29 22:39

    ES6

    Matrix m with size 3 rows and 5 columns (remove .fill(0) to not init by zero)

    [...Array(3)].map(x=>Array(5).fill(0))       
    

    let Array2D = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));
    
    let m = Array2D(3,5);
    
    m[1][0] = 2;  // second row, first column
    m[2][4] = 8;  // last row, last column
    
    // print formated array
    console.log(JSON.stringify(m)
      .replace(/(\[\[)(.*)(\]\])/g,'[\n  [$2]\n]').replace(/],/g,'],\n  ')
    );

提交回复
热议问题