假设我有这个创建网格的类:
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)
答案 0 :(得分:0)
如果您想要返回一个数组,那么最好将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' ]
// ]
答案 1 :(得分:0)
您可以使用普通数组和工厂方法:
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