【发布时间】:2021-04-30 12:17:34
【问题描述】:
场景
我有以下代码:
const composeMatrix = (nRow, nCol, filler) => Array(nRow).fill(Array(nCol).fill(filler));
class Matrix extends Array {
constructor({ nRows = 3, nCols = 3, filler = 0 } = {}) {
super(...composeMatrix(nRows, nCols, filler));
}
makeTranspose() {
const mat = this;
const column = mat[0];
return column.map((_, i) => {
return mat.map((row) => row[i]);
});
}
}
我正在像这样实例化一个新的Matrix:
const mat = new Matrix({ nRows: 4, filler: 1 });
将mat 记录到控制台给了我预期的结果,
Matrix(4) [
[ 1, 1, 1 ],
[ 1, 1, 1 ],
[ 1, 1, 1 ],
[ 1, 1, 1 ]
]
问题
现在,当我调用该类的 makeTranspose 方法时,它会返回:
[
Matrix(4) [ 1, 1, 1, 1 ],
Matrix(4) [ 1, 1, 1, 1 ],
Matrix(4) [ 1, 1, 1, 1 ]
]
预期输出:
Matrix(3) [
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 1 ]
]
我的想法是,map函数每次遍历数组时都会调用这个子类的构造函数,然后调用super,然后调用composeMatrix函数并生成一个新的矩阵。
我该如何解决这个问题?
- 我想要一个
class来扩展Array并添加一些方法。 - 构造函数需要按预期获取一些相关参数和函数。
- 我不想向
prototype添加函数。
【问题讨论】:
-
为什么要扩展
Array?矩阵不是数组。这打破了Liskov substitution principle。
标签: javascript arrays class oop constructor