1.递归
function flattenArray(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flattenArray(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
// 示例
const array = [1, [2, 3], [4, [5, 6]]];
const newArray = flattenArray(array);
console.log(newArray); // 输出: [1, 2, 3, 4, 5, 6]
2. ES6的方法flat
const array = [1, [2, 3], [4, [5, 6]]];
const newArray = array.flat(Infinity);
console.log(newArray); // 输出: [1, 2, 3, 4, 5, 6]
3. 数组reduce方法
const array = [1,9,[1, 2], [3, [4, 5]], 6];
const newArray = array.reduce((acc, curr) => acc.concat(curr), []);
console.log(newArray); // 输出 [1,9,1,2,3,4,5,6]