Declare an empty two-dimensional array in Javascript?

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

    var arr = [];
    var rows = 3;
    var columns = 2;
    
    for (var i = 0; i < rows; i++) {
        arr.push([]); // creates arrays in arr
    }
    console.log('elements of arr are arrays:');
    console.log(arr);
    
    for (var i = 0; i < rows; i++) {
        for (var j = 0; j < columns; j++) {
            arr[i][j] = null; // empty 2D array: it doesn't make much sense to do this
        }
    }
    console.log();
    console.log('empty 2D array:');
    console.log(arr);
    
    for (var i = 0; i < rows; i++) {
        for (var j = 0; j < columns; j++) {
            arr[i][j] = columns * i + j + 1;
        }
    }
    console.log();
    console.log('2D array filled with values:');
    console.log(arr);

提交回复
热议问题