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

实现 Iterator 用于遍历 #116

Open
Genluo opened this issue May 22, 2023 · 0 comments
Open

实现 Iterator 用于遍历 #116

Genluo opened this issue May 22, 2023 · 0 comments

Comments

@Genluo
Copy link
Owner

Genluo commented May 22, 2023

如果我们需要使用 for of 遍历一个对象,需要为对象实现相应 Symbol.iterator 接口实现,例如下面这种方式:

function objectIterator() {
  const keys = Object.keys(this)
  let index = 0
  return {
    next: () => {
      const done = index >= keys.length
      const value = done ? undefined : this[keys[index]]
      index++
      return {
        done,
        value
      }
    }
  }
}

Object.prototype[Symbol.iterator] = objectIterator

const obj = {
  key: '1',
  value: '2'
}

for (const iterator of obj) {
  console.log(iterator)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant