js 扁平化输出数组

1.使用数组的flat方法

[1,2,[3,[4,5]]].flat(Infinity)  //[1, 2, 3, 4, 5]

2.实现方式二:

  var arr = [[1, 2, 23], [13, 4, 5, 5], [6, 7, 9, [11, 12, [12, 13, [14]]]], 10];
  var result = [];
  function flatFn(arr,res=[]) {
      arr.forEach(item => {
        if (Array.isArray(item)) {
          flatFn(item,res);
        } else {
          res.push(item)
        }
      })
    return res;
  }
  result = flatFn(arr);
  console.log("result", result)
发布了82 篇原创文章 · 获赞 10 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/xin_yun_Jian/article/details/103620477