1. 程式人生 > >取出巢狀陣列的所有成員

取出巢狀陣列的所有成員

const tree = ['a', ['b', ['c', ['d']]], 'e'];

方法一:

const arr1 = tree.flat(Infinity); //["a", "b", "c", "d", "e"]

方法二:

  function* iterTree(tree) {
    if(Array.isArray(tree)) {
      for(let i = 0, len = tree.length; i < len; i++) {
        yield* iterTree(tree[i]);
      }
    } else {
      yield tree;
    }
  }

  for(let x of iterTree(tree)) {
    console.log(x); //"a" "b" "c" "d" "e"
  }