前端面试题:扁平化多维数组

109 阅读1分钟

什么是数组扁平化?

数组的扁平化其实就是将一个嵌套多层的数组 array(嵌套可以是任何层数)转换为只有一层的数组

递归思路很容易理解,就是通过循环递归的方式,一项一项地去[遍历],如果每一项还是一个数组,那么就继续往下遍历,利用递归程序的方法,来实现数组的每一项的连接

<!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>
    /* 数组扁平化 将多维数组拍成一维数组 多维数组:数组里面的元素还是一个数组 [1,2,3, [4,5, [6,7]]]
    [1,2,3,4,5,6,7] 思路:看看 arr 数组里面的元素 到底是不是一个数组 如果不是 数组 就将它 放入到
    newArr 里面 如果数组里面的元素是数组 进入到这个数组里面的 将数组的元素取出来 // 一直在重复的执行 
    函数的代码 */ 
    const arr = [1, 2, 3, [4, 5, [6, 7, [8, 9]]]] 
    // console.log(typeof arr) 
    const newArr = [] 
    function f(data) { 
    // 遍历数组 
    data.forEach(item => { 
    // 判断数组元素 到底是不是数组 
    if (Array.isArray(item)) { 
    // 表示 item 是数组 再次的调用 f函数 f(item) } else { 
    // 表示 item 不是数组
    newArr.push(item) 
       } 
  }) 
} 
f(arr)
console.log(newArr) 
 </script>
</body> 
</html>