首页 > 编程语言 > 详细

[Javascript] Avoid Nested For Loops with Generators

时间:2020-01-08 17:27:50      阅读:95      评论:0      收藏:0      [点我收藏+]

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

 

[Javascript] Avoid Nested For Loops with Generators

原文:https://www.cnblogs.com/Answer1215/p/12167371.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!