How can I create a two dimensional array in JavaScript?

后端 未结 30 4281
天涯浪人
天涯浪人 2020-11-21 05:25

I have been reading online and some places say it isn\'t possible, some say it is and then give an example and others refute the example, etc.

  1. How do I dec

30条回答
  •  一向
    一向 (楼主)
    2020-11-21 05:41

    The sanest answer seems to be

    var nrows = ~~(Math.random() * 10);
    var ncols = ~~(Math.random() * 10);
    console.log(`rows:${nrows}`);
    console.log(`cols:${ncols}`);
    var matrix = new Array(nrows).fill(0).map(row => new Array(ncols).fill(0));
    console.log(matrix);


    Note we can't directly fill with the rows since fill uses shallow copy constructor, therefore all rows would share the same memory...here is example which demonstrates how each row would be shared (taken from other answers):

    // DON'T do this: each row in arr, is shared
    var arr = Array(2).fill(Array(4));
    arr[0][0] = 'foo'; // also modifies arr[1][0]
    console.info(arr);
    

提交回复
热议问题