js手动配置迭代器接口

对象内添加:

//给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 }
    	}
  	}
  }
}
发布了218 篇原创文章 · 获赞 35 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_41614928/article/details/104234093