zoukankan      html  css  js  c++  java
  • [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!!!
    */
  • 相关阅读:
    C++中const变量使用注意
    const对象调用static成员函数
    Error in startup script: value for " " missing
    check tcl version
    socket
    grid pack
    mouse bind
    gesture
    pixel
    open
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12167371.html
Copyright © 2011-2022 走看看