Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

迭代协议 #10

Open
hengg opened this issue Sep 2, 2020 · 0 comments
Open

迭代协议 #10

hengg opened this issue Sep 2, 2020 · 0 comments

Comments

@hengg
Copy link
Owner

hengg commented Sep 2, 2020

迭代器和生成器

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant