我有一个构造函数:

function a(x, y){\n
    this.array[x][y];
     for(var i = 0; i<x; i++){
         for(var j = 0l j<y; j++){
             this.array[i][j]=0;
         }
     }
}


我如何正确声明this.array?
(this.array应该是多维数组。

最佳答案

如果要初始化该数组,请使用以下方法:

                         +---- Length for outter array
                         |
                         v
this.array = Array.from({length: x}, () => Array(y).fill(0));
                                                ^
                                                |
                                                +--- This will initialize the nested arrays




function a(x, y){
  this.array = Array.from({length: x}, () => Array(y).fill(0));
  console.log(JSON.stringify(this.array, null, 2))
}

a(2, 3);

.as-console-wrapper { max-height: 100% !important; top: 0; }

10-04 22:21
查看更多