zoukankan      html  css  js  c++  java
  • generator小结

    1. generator传参和next传参

    genTest();
    
    function genTest(){
        let g = gen(0); //0为普通函数参数
        console.log('next: ', g.next(10)); //第一个next执行第一个yield之前的代码,10不被采用,无效
        console.log('next: ', g.next(20)); //第二个next执行第二个yield之前,第一个yield之后的代码,20被赋值给第一个yield等号左侧的a,所以a等于20
        console.log('next: ', g.next(30)); //next传入的值只对yield左侧的值有影响,对yield的右侧值,及返回值无影响
        console.log('next: ', g.next(40)); //next不传值,则yield左侧的值为undefined
    }
    
    function* gen(p){
        console.log('1',p);
        var a = yield 100;
        console.log('a', a);
        var b = yield 200;
        console.log('b', b);
        var c = yield 300;
        console.log('c',c);
    }   

    输出

    1 0
    next:  {value: 100, done: false}  //不受next传入值影响
    a 20                         
    next:  {value: 200, done: false}  
    b 30
    next:  {value: 300, done: false}  
    c 40
    next:  {value: undefined, done: true} 

    2. generator经典实例

    // 斐波那契竖列生成器
    function* fib() {
        let [x, y] = [0, 1];
        while (true) {
          yield x;
          [x, y] = [y, x + y];
        }
    }
    
    // 阶乘
    function* factorial() {
        let n = 1;
        let fac = 1;
        while (true) {
            yield fac;
            fac = fac * ++n;
        }
    } 

  • 相关阅读:
    接口与抽象类的区别
    全排列(按字典序)
    设置mysql数据库的密码
    android中操作SQLite注意事项
    Android: Fragment详解
    android设置组件所占的比例
    九度oj 1482:玛雅人的密码
    ACM模板
    洛谷 P1156 垃圾陷阱
    AtCoder Beginner Contest 187 F
  • 原文地址:https://www.cnblogs.com/mengff/p/14850235.html
Copyright © 2011-2022 走看看