实现数组扁平化的三种方法

221 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const arr = [1, 2, 3, [4, 5, [6, 7, 8]]];

      // 1.es6 flat
      console.log(arr.flat(Infinity)); //[1, 2, 3, 4, 5, 6, 7, 8]

      //2.
      let res = JSON.stringify(arr).replace(/\[|\]/g, "");
      console.log(res); //1,2,3,4,5,6,7,8
      res = JSON.parse("[" + res + "]");

      console.log(res);

      //3.reduce 方法:
      function flatten(arr) {
        return arr.reduce((result, item) => {
          return result.concat(Array.isArray(item) ? flatten(item) : item);
        }, []);
      }
      console.log("reduce", flatten(arr));
    </script>
  </body>
</html>