我想在此Board类中创建并填充两个三维数组,但是我的方法似乎不起作用。它只返回一个函数而不是一个值。我应该通过方法而不是在类构造函数中执行此操作吗?
class Board{
constructor(width,height,cols,rows)
{
this.width=width;
this.height=height;
this.cols=cols;
this.rows=rows;
this.array= function(){
let array=[];
for(let i=0;i<this.cols;i++)
{
array[i]=[];
for(let j=0;j<this.rows;j++){
array[i][j]=0;
}
}
return array;
}
}
答案 0 :(得分:4)
不需要内部函数,只需填充数组并将其分配给属性即可。
class Board {
constructor(width, height, cols, rows) {
this.width = width;
this.height = height;
this.cols = cols;
this.rows = rows;
let array = [];
for (let i = 0; i < this.cols; i++) {
array[i] = [];
for (let j = 0; j < this.rows; j++) {
array[i][j] = 0;
}
}
this.array = array;
}
}
const b = new Board(2, 3, 4, 5);
console.log(b.array);
答案 1 :(得分:0)
可以更容易
class Board {
constructor(width, height, cols, rows) {
this.width = width;
this.height = height;
this.cols = cols;
this.rows = rows;
this.array = [];
for (let i = 0; i < this.cols; i++) {
this.array.push(new Array(this.rows).fill(0));
}
}
答案 2 :(得分:0)
您可以直接将值放在属性上而无需运行
class Board {
constructor(width, height, cols, rows) {
this.width = width;
this.height = height;
this.cols = cols;
this.rows = rows;
let array = new Array(this.cols).fill(0).map(val=> new Array(this.rows).fill(0))
this.array = array;
}
}
const b = new Board(2, 3, 4, 5);
console.log(b.array);
答案 3 :(得分:0)
this.array= function(){
let array=[];
for(let i=0;i<this.cols;i++)
{
array[i]=[];
for(let j=0;j<this.rows;j++){
array[i][j]=0;
}
}
return array;
}
这只会创建一个名为this.array
的函数。
如果您希望this.array
保留返回值,请直接在其中调用该函数。
this.array= (function(){
let array=[];
for(let i=0;i<this.cols;i++)
{
array[i]=[];
for(let j=0;j<this.rows;j++){
array[i][j]=0;
}
}
return array;
})();