How can I create a two dimensional array in JavaScript?

后端 未结 30 4272
天涯浪人
天涯浪人 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:35

    To create a non-sparse "2D" array (x,y) with all indices addressable and values set to null:

    let 2Darray = new Array(x).fill(null).map(item =>(new Array(y).fill(null))) 
    

    bonus "3D" Array (x,y,z)

    let 3Darray = new Array(x).fill(null).map(item=>(new Array(y).fill(null)).map(item=>Array(z).fill(null)))
    

    Variations and corrections on this have been mentioned in comments and at various points in response to this question but not as an actual answer so I am adding it here.

    It should be noted that (similar to most other answers) this has O(x*y) time complexity so it probably not suitable for very large arrays.

提交回复
热议问题