自定义迭代器
// 自定义迭代器class CountItem {constructor (item) {this.item = itemthis.count = 1}next () {// 判断if (this.count <= this.item) {return {done: false, value: this.count++}} else {return {done: true, value: undefined}}}[Symbol.iterator]() {// 调用这个接口,返回tihs,// this本身具有 next() 方法,也就是迭代器方法return this}}let arr = new CountItem(3)for (let i of arr) {console.log(i)}
// 以上方法出现的问题// 一个实例化对象,只能迭代一次。// 解决问题,在没创建一个迭代器时候,就对应着一个新的计数器。然后将计数器比变量放到闭包里// 通过闭包返回迭代器class CountItem {constructor (item) {this.item = item}[Symbol.iterator]() {// 使用item闭包let count = 1,item = this.itemreturn {next () {// 判断if (count <= item) {return {done: false, value: count++}} else {return {done: true, value: undefined}}}}}}let arr = new CountItem(3)console.log([...arr])
