yield*运用

选自阮一峰大神书籍 ECMAScript 6 入门node

运用一:中序遍历彻底二叉树

定义Treees6

class Tree {
  constructor (left, label, right) {
    this.left = left;
    this.label = label;
    this.right = right;
  }
}
复制代码

遍历中序函数数组

function* inorder(tree) {
  if (tree) {
    yield* inorder(tree.left);
    yield tree.label;
    yield* inorder(tree.right);
  }
}
复制代码

生成二叉树函数

function make(array) {
  return array.length == 1 ?
    new Tree(null, array[0], null) :
    new Tree(make(array[0]), array[1], make(array[2]));
}
let tree = make([[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]]);
复制代码

遍历二叉树ui

let result = [];
for (let node of inorder(tree)) {
  result.push(node);
}
// ["a", "b", "c", "d", "e", "f", "g"]
复制代码

运用二:平铺深度嵌套的数组

function* iterateNestedArray(tree) {
    if (Array.isArray(tree)) {
        for(let array of tree) {
            yield* iterateNestedArray(array);
        }
    } else yield tree;
}
// test
let tree = [[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]];
[...iterateNestedArray(tree)];
// ["a", "b", "c", "d", "e", "f", "g"]
复制代码

还可运用Array.prototype.flat()方法实现this

let tree = [[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]];
tree = tree.flat(Infinity);
// ["a", "b", "c", "d", "e", "f", "g"]
复制代码

Note: yield*表达式至关for...of二者均调用了数据部署的Iterator接口,进行遍历的。spa

相关文章
相关标签/搜索