選自阮一峯大神書籍 ECMAScript 6 入門node
定義
Tree
類es6
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