>假设我有这样一个制作网格的类:
class Grid {
constructor(w, h, fill) {
this.w = w;
this.h = h;
this.fill = fill;
this.value = new Array(w).fill(null).map(() => new Array(h).fill(fill));
}
addAll() {
let sum = 0;
this.value.forEach(row => row.forEach(n => sum += n));
return sum;
}
}
下面是一个正在使用的示例:
const myGrid = new Grid(2, 3, 1); // Creates a 2x3 grid made out of 1s
myGrid.addAll(); // 6
myGrid.value; // [[1, 1, 1], [1, 1, 1]]
我想知道是否有办法完全跳过myGrid.value
,而是在它仍然返回相同内容的地方使用 myGrid
。
您可以在数组构造函数中看到以下内容:
const myArray = new Array(3).fill(1);
myArray; // [1, 1, 1] (Notice it's not myArray.value)
如果你想返回一个数组,最好把grid
写成一个普通函数而不是一个类
const grid = (rows, cols, value) =>
rows === 0
? []
: [ Array(cols).fill(value) ] .concat (grid (rows - 1, cols, value))
console.log (grid (2, 3, 1))
// [ [ 1, 1, 1 ]
// , [ 1, 1, 1 ]
// ]
console.log (grid (4, 4, 'x'))
// [ [ 'x', 'x', 'x', 'x' ]
// , [ 'x', 'x', 'x', 'x' ]
// , [ 'x', 'x', 'x', 'x' ]
// , [ 'x', 'x', 'x', 'x' ]
// ]
您可以使用普通数组和工厂方法:
class Grid {
static of (w, h, fill) {
return new Array(w).fill(null).map(() => new Array(h).fill(fill));
}
static addAll(grid) {
let sum = 0;
grid.forEach(row => row.forEach(n => sum += n));
return sum;
}
}
const grid = Grid.of(3, 2, 1);
const sum = Grid.addAll(grid);
console.log(grid); // [[1, 1], [1, 1], [1, 1]]
console.log(sum); // 6