Skip to content

迭代协议 #10

@hengg

Description

@hengg

迭代器和生成器

const obj = {'a':'a','b':'b'};
// obj[Symbol.iterator] 是可迭代协议
obj[Symbol.iterator] = function() {
  const that = this;
  const keys = Object.keys(this);
  // 返回的对象则是迭代器协议
  return {
    next: function() {
      if (this._idx !== keys.length) {
        return { value: that[keys[this._idx++]], done: false };
      } else {
        return { done: true };
      }
    },
    _idx: 0,
  };
};

for (const element of obj) {
  console.log(element);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions