[Javascript] Avoid Nested For Loops with Generators

Generators allow you to hook together multiple generators with the yield* syntax. This allows you to branch off into many different types of iterations within the main iteration and covers complex scenarios where you usually end up reaching for nested for loops.

const abcs = ["A", "B", "C"]

const shoutIterator = function* (word: string) {
    yield word + "!"
    yield word + "!!"
    yield word + "!!!"
}

const reverseIterator = function* (array: string[]) {
    let reversed = array.reverse();
    yield* shoutIterator(array[0]);
    yield* shoutIterator(array[1]);
    yield* shoutIterator(array[2]);
}

const iterator = reverseIterator(abcs)

for (let value of iterator) {
    console.log(value)
}
/*
C!
 C!!
 C!!!
 B!
 B!!
 B!!!
 A!
 A!!
 A!!!
*/
原文地址:https://www.cnblogs.com/Answer1215/p/12167371.html