// 生成器
// 生成器与迭代器使用方法一样
// function* gen() {
// yield Promise.resolve('1') // 接同步代码异步代码都可以
// yield '2'
// yield '3'
// }
// const man = gen()
// done表示是否生成完成,生成器调用next会一步一步返回对应的值和done值,当全部完成会返回done:true
// console.log(man.next()); // {value: Promise{'1'}, done: false}
// console.log(man.next()); // {value: '2', done: false}
// console.log(man.next()); // {value: '3', done: false}
// console.log(man.next()); // {value: undefined, done: true}
// set、map、数组、argument、NodeList伪数组查看prototype都有迭代器Symbol.iteratior
// const set:Set<number> = new Set([1,1,2,3,3,3])
// const each = (value:any) => {
// let it:any = value[Symbol.iterator]() // 获取需要迭代的迭代器,是个函数
// let next:any = {done: false} // 定义next
// while(!next.done) { // 如果还没到迭代到完成
// next = it.next() // 获取迭代到哪一步
// if(!next.done) {
// console.log(next.value); // 输出值
// }
// }
// }
// each(set) //1,2,3
// 迭代器的语法糖 for of,
// for (const element of set) {
// console.log(element);
// }
// for of不可以使用在对象上,因为对象上没有Symbol.iterator
// const obj2 = {
// name: '1'
// }
// for (const element of obj2) {
// }
// 数组的解构也是调用迭代器Symbol.iterator
// const [l,b,c] = [1,2,3]
// console.log(l,b,c); //1,2,3
// 给对象加上迭代器
const obj1 = {
max: 5,
current: 0,
[Symbol.iterator]() {
return{
max: this.max,
current: this.current,
next() {
if(this.current === this.max){
return {done: true}
} else {
return {
value: this.current++,
done: false
}
}
}
}
}
}
for (const element of obj1) {
console.log(element); //0,1,2,3,4
}