javascript - 解释如何拆包属性(property)

标签 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;
    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}提取每个字段。

关于javascript - 解释如何拆包属性(property),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141502/

相关文章:

reference - 循环变量之前 `&`的作用是什么?

javascript - Node JS/V8 解构错误?

javascript - 使用解构对象中的对象和键解构参数?

javascript - Firebase 身份验证有效但不断刷新页面

javascript - ngOptions - 值未定义

javascript - PHP 未从 AJAX 接收序列化数据

javascript - 输入文件大小和内容不会在 macOS 上更新

javascript - 如何保护代码免于解构 Javascript 中的空值?

Java对象解构

javascript - 在 Javascript 中将像素存储在椭圆形中的算法是什么?