Declare an empty two-dimensional array in Javascript?

后端 未结 18 1383
暖寄归人
暖寄归人 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:32

    If you want to be able access the matrix like so matrix[i][j]

    I find it the most convinient to init it in a loop.

    var matrix = [],
        cols = 3;
    
    //init the grid matrix
    for ( var i = 0; i < cols; i++ ) {
        matrix[i] = []; 
    }
    

    this will give you [ [], [], [] ]

    so matrix[0][0] matrix[1][0] return undefined and not the error "Uncaught TypeError: Cannot set property '0' of undefined"

提交回复
热议问题