[英]How to create a constructor that returns a value without accessing a property
假設我有創建網格的此類:
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
地方使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.