解释 属性 是如何解包的

Explain how the property is being unpacked

我不确定 value 是如何解压的:

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}`)
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

因为 for (let obj of matrix) 为您提供了在这一行 let value = {x: this.x, y: this.y, value: this.matrix.get(this.x, this.y)}; 中构建的对象,进入每个循环迭代,然后解构语法 {y, x, value} 提取每个字段。