Skip to content

迭代器

js
const [a, b] = {
  a: 3,
  b: 4,
};

让其成立

我的答案

js
{
  a: 1,
  b: 2,
  [Symbol.iterator]() {
    let index = 0;
    console.log("iterator", index);
    return {
      next: function () {
        console.log("next", index);
        switch (index) {
          case 0: {
            index++;
            console.log("a is", this.a);
            return {
              value: this.a,
              done: false,
            };
          }

          case 1: {
            index++;
            return {
              value: this.b,
              done: false,
            };
          }

          default:
            return { done: true };
        }
      }.bind(this),
    };
  },
};

优秀答案

js
Object.prototype[Symbol.iterator] = function () {
  return Object.values(this)[Symbol.iterator]();
};

优秀答案

js
Object.prototype[Symbol.iterator] = function* () {
  yield* Object.values(this);
};