How do you easily create empty matrices javascript?

前端 未结 17 1448
[愿得一人]
[愿得一人] 2020-12-04 16:29

In python, you can do this:

[([None] * 9) for x in range(9)]

and you\'ll get this:

[[None, None, None, None, None, None, No         


        
17条回答
  •  生来不讨喜
    2020-12-04 17:00

    There is something about Array.fill I need to mention.

    If you just use below method to create a 3x3 matrix.

    Array(3).fill(Array(3).fill(0));
    

    You will find that the values in the matrix is a reference.


    Optimized solution (prevent passing by reference):

    If you want to pass by value rather than reference, you can leverage Array.map to create it.

    Array(3).fill(null).map(() => Array(3).fill(0));
    

提交回复
热议问题