我对这个陈述是如何工作的有点困惑this.content[y * width + x] = element(x, y));
class Matrix {
constructor(width, height, element = (x, y) => undefined) { this.width = width; this.height = height; this.content = [];
//console.log(this.content);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
this.content[y * width + x] = element(x, y);
console.log(this.content[y * width + x] = element(x, y));
}
}
}
get(x, y) { return this.content[y * this.width + x]; } set(x, y, value) { this.content[y * this.width + x] = value; } }
class MatrixIterator { constructor(matrix) { this.x = 0; this.y = 0; this.matrix = matrix; } next() { if (this.y == this.matrix.height) return {done: true}; let value = {x: this.x, y: this.y, value: this.matrix.get(this.x, this.y)};
this.x++; if (this.x == this.matrix.width) { this.x = 0; this.y++; } return {value, done: false}; } }
Matrix.prototype[Symbol.iterator] = function() { return new MatrixIterator(this); };
//We can now loop over a matrix with for/of.
let matrix = new Matrix(2, 2, (x, y) => `value ${x},${y}`);
console.log(matrix);
for (let {x, y, value} of matrix) { console.log(x, y, value);
}
// → 0 0 value 0,0
// → 1 0 value 1,0
// → 0 1 value 0,1
// → 1 1 value 1,1
要识别矩阵的每个元素,显然需要使用索引,在这里本书的作者你在哪里找到这个,选择了这种方法来做到这一点:
y * this.width + x
这允许您访问矩阵的确定元素,同时识别所有元素,并保证不会与 .
重叠或者,您可以使用:[y + '_' + x]
这样做与y * this.width + x
的目的完全相同, 但是转换为字符串和串联使用循环来完成只需 2 个操作即可完成的事情!y * this.width
和result + x
. 这是用我的索引方式重写您的代码:
class Matrix {
constructor(width, height, element = (x, y) => undefined) {
this.width = width;
this.height = height;
this.content = {};//you need this for string keys !
//console.log(this.content);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
this.content[y +'_'+ x] = element(x, y);
console.log((this.content[y +'_'+ x] = element(x, y)));
}
}
}
get(x, y) {
return this.content[y +'_'+ x];
}
set(x, y, value) {
this.content[y +'_'+ x] = value;
}
}
class MatrixIterator {
constructor(matrix) {
this.x = 0;
this.y = 0;
this.matrix = matrix;
}
next() {
if (this.y == this.matrix.height) return { done: true };
let value = {
x: this.x,
y: this.y,
value: this.matrix.get(this.x, this.y),
};
this.x++;
if (this.x == this.matrix.width) {
this.x = 0;
this.y++;
}
return { value, done: false };
}
}
//We can now loop over a matrix with for/of.
let matrix = new Matrix(2, 2, (x, y) => `value ${x},${y}`);
console.log('Matrix formed is : ',matrix);