zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Avoid Nested For Loops with Generators

JavaScript for with nested avoid
2023-09-14 09:00:48 时间

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!!!
*/