[Javascript] Create Your First Iterator in JavaScript

Iterators are the foundation of generators. Much of the misunderstanding around generators comes from the lack of understanding iterators. An iterator has a Symbol.iterator property with an object that contains a next method which defines what is output each iteration.

let i = 0

const next = () => ({
    value: i++,
    done: i > 10
})

const iterator = {
    [Symbol.iterator]() {
        return {
            next
        }
    }
}

for (let value of iterator) {
    console.log(value)
}

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12111166.html