我有一个构造函数:
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; }
关于javascript - 如何将多维数组放入对象构造函数Javascript中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49118564/