TypeScript基本知识(3)

55 阅读1分钟

生成器

function* gen() { 
    yield Promise.resolve('小满')
    yield '大满'
    yield '塞满了'
}
const man = gen()
console.log(man.next()) // { value: Promise { '小满' }, done: false }
console.log(man.next()) // { value: '大满',done: false }
console.log(man.next()) // { value: '塞满了',done: false }
console.log(man.next()) // { value: undefied,done: true }

迭代器

// 手写forEach
const each = (value: any) => { 
    let It: any = value[Symbol.iterator]()
    let next: any = { done: false }
    while (!next.done) { 
        next = It.next()
        if (!next.done) { 
            console.log(next.value)
        }
    }
}
each(set)

// 对象转成可迭代对象
let obj1 = {
    max: 5,
    current: 0,
    [Symbol.iterator]() { 
        return {
            max: this.max,
            current: this.current,
            next() { 
                if (this.current === this.max) {
                    return { value: undefined, done: true }
                } else { 
                    return { value: this.current++, done: false }
                }
            }
        }
    }
}