How can I create a two dimensional array in JavaScript?

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

    For one liner lovers Array.from()

    // creates 8x8 array filed with "0"    
    const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"))
    

    Another one (from comment by dmitry_romanov) use Array().fill()

    // creates 8x8 array filed with "0"    
    const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"))
    

    Using ES6+ spread operator ("inspired" by InspiredJW answer :) )

    // same as above just a little shorter
    const arr2d = [...Array(8)].map(() => Array(8).fill("0"))
    

提交回复
热议问题