对象内添加:
//给Object添加迭代器
Object.prototype[Symbol.iterator] = function () {
let keys = Object.keys(this)
let that = this, index = 0
return {
next() {
if (index < keys.length) return { value: that[keys[index++]], done: false }
else return { value: undefined, done: true }
}
}
}
类里面添加:
//手动配置迭代器接口
class Stack{
constructor() {
this.count = 0 //长度
this.items = {} //迭代的对象
}
[Symbol.iterator]() {
let self = this
let index = 0
return {
next() {
if (index < self.count) return { value: self.items[index++], done: false }
else return { value: undefined, done: true }
}
}
}
}