取出嵌套数组的所有成员

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"
  }

猜你喜欢

转载自blog.csdn.net/Wangdanting123/article/details/85255026