zoukankan      html  css  js  c++  java
  • ES6知识点整理之----Generator----yield*表达式

    1、在 Generator 函数内部,调用另一个 Generator 函数,默认情况下是没有效果的

    2、yield*表达式:用来在一个 Generator 函数里面执行另一个 Generator 函数。

    function* bar() {
      yield 'x';
      yield* foo();
      yield 'y';
    }
    
    // 等同于
    function* bar() {
      yield 'x';
      yield 'a';
      yield 'b';
      yield 'y';
    }
    
    // 等同于
    function* bar() {
      yield 'x';
      for (let v of foo()) {
        yield v;
      }
      yield 'y';
    }
    
    for (let v of bar()){
      console.log(v);
    }
    // "x"
    // "a"
    // "b"
    // "y"

    从语法角度看,如果yield表达式后面跟的是一个遍历器对象,需要在yield表达式后面加上星号,表明它返回的是一个遍历器对象。这被称为yield*表达式。

    3、yield*后面的 Generator 函数(没有return语句时),等同于在 Generator 函数内部,部署一个for...of循环。

    4、如果被代理的 Generator 函数有return语句,那么就可以向代理它的 Generator 函数返回数据。

    5、如果yield*后面跟着一个数组,由于数组原生支持遍历器,因此就会遍历数组成员。实际上,任何数据结构只要有 Iterator 接口,就可以被yield*遍历。

    6、yield*命令可以很方便地取出嵌套数组的所有成员。

    function* iterTree(tree) {
      if (Array.isArray(tree)) {
        for(let i=0; i < tree.length; i++) {
          yield* iterTree(tree[i]);
        }
      } else {
        yield tree;
      }
    }
    
    const tree = [ 'a', ['b', 'c'], ['d', 'e'] ];
    
    for(let x of iterTree(tree)) {
      console.log(x);
    }
    // a
    // b
    // c
    // d
    // e
  • 相关阅读:
    Boliuraque OI 总结
    HNU 1447 最长上升路径
    妹纸
    某个子串的循环节
    跳石头
    小澳的葫芦
    递推式的循环问题
    BZOJ 2326 数学作业
    BZOJ 2337 XOR和路径
    hdu5468 Puzzled Elena
  • 原文地址:https://www.cnblogs.com/adhehe/p/9681429.html
Copyright © 2011-2022 走看看