Javascript 解释如何解包该属性
我不确定该值是如何解压缩的:Javascript 解释如何解包该属性,javascript,destructuring,Javascript,Destructuring,我不确定该值是如何解压缩的: for (let {y,x, value} of matrix) { console.log(x, y, value); } 它如何知道从Matrix.prototype[Symbol.iterator]的next.value.value中提取它 class Matrix { constructor(width, height, element = (x, y) => undefined) { this.width = width;
for (let {y,x, value} of matrix) {
console.log(x, y, value);
}
它如何知道从Matrix.prototype[Symbol.iterator]的next.value.value中提取它
class Matrix {
constructor(width, height, element = (x, y) => undefined) {
this.width = width;
this.height = height;
this.content = [];
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
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;
}
}
let obj = new Matrix(2, 2, (x, y) => `value ${x},${y}`)
因为for let obj of matrix给了你在这行中构建的对象let value={x:this.x,y:this.y,value:this.matrix.getthis.x,this.y};,在每次循环迭代中,然后使用解构语法{y,x,value}提取每个字段。因为of的工作原理,它被设计为迭代一个iterable。
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);
};
let matrix = new Matrix(2, 2, (x, y) => `value ${x},${y}`);
for (let {y,x, 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