zoukankan      html  css  js  c++  java
  • Generator函数

    Generator 函数是一个状态机,封装了多个内部状态。

    执行 Generator 函数会返回一个遍历器对象。

    最简单的例子

    function * loop () {
      for (let i = 0; i < 5; i++) {
        yield console.log(i)
      }
    }
    
    let l = loop()
    l.next()
    l.next()
    l.next()

    0
    1
    2

    yield 表达式  的结果为undefined

    function * gen () {
      let a = yield 1
      console.log(a)
    }
    
    let g = gen()
    g.next()
    g.next()
    
    undefined

    yield后面可以接星号*,*号后面若是数组,代表遍历数组,后面也可以是generator函数

    function * gen () {
      yield * [1, 2, 3] // 相当于yield 1 yield 2 yield 3
    }
    
    let g = gen()
    console.log(g.next())
    console.log(g.next())
    
    Object { value: 1, done: false }
    Object { value: 2, done: false }

    因为yield可以控制Generator函数的暂停,所以Generator函数是可以在运行时改变参数的,用next方法传入想要修改的值,即改变yield 表达式的返回值

    function * gen () {
      let a = yield 1
      console.log(a)
    }
    
    let g = gen()
    g.next()
    g.next(2)
    
    2
  • 相关阅读:
    2014/11/25 函数
    2014/11/24 条件查询
    2、计算器
    1、winform数据库调用(基本方法)
    1、网页基础
    14、函数输出参数、递归
    13、C#简易版 推箱子游戏
    12、函数
    11、结构体、枚举
    10、特殊集合
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/13252513.html
Copyright © 2011-2022 走看看