数组扁平化是指将多层嵌套的数组转换为只有一层的数组。你可以使用递归或者数组的一些内置方法来实现这个功能。以下是几种常见的方法:
1. 使用递归实现:
function flattenArray(arr) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
result = result.concat(flattenArray(item));
} else {
result.push(item);
}
});
return result;
}
const nestedArray = [1, [2, [3, 4]], 5, [6]];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]
2. 使用reduce()方法:
function flattenArray(arr) {
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}
const nestedArray = [1, [2, [3, 4]], 5, [6]];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]
3. 使用ES6的flat()方法(注意兼容性):
const nestedArray = [1, [2, [3, 4]], 5, [6]];
const flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]
这些方法中,递归方法在处理大型数组时可能会有性能问题,而使用reduce()方法则比较灵活,而ES6的flat()方法简洁方便。选择哪种方法取决于你的需求和对浏览器兼容性的要求
这里最简便,用的人最多,flat方法。