没有指定层数的数组扁平化
let arr = [1, [2, [1, 2, 3, [4, 5, 6]]], 18, [25, 12, [13, 14, 27]]] function flatten(arr) { let res = [] for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { res = res.concat(flatten(arr[i])) } else { res.push(arr[i]) } } return res } console.log(flatten(arr));
带有层数的数组扁平化
let arr = [1, [2, [1, 2, 3, [4, 5, 6]]], 18, [25, 12, [13, 14, 27]]] function flatten(arr, k) { if (k == 0) { return arr } let res = [] for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { res = res.concat(flatten(arr[i], k - 1)) } else { res.push(arr[i]) } } return res } console.log(flatten(arr, 2));