在 JavaScript 中,有多种方法可以将嵌套的数组扁平化,即将多层嵌套的数组转换为一个一维数组。下面介绍几种常用的方法:
方法一:使用递归
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 nestedArray = [1, 2, [3, 4, [5, 6]]];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
方法二:使用 `Array.prototype.flat()` 方法(ES2019+)
const nestedArray = [1, 2, [3, 4, [5, 6]]];
const flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
方法三:使用 `Array.prototype.reduce()` 方法
const nestedArray = [1, 2, [3, 4, [5, 6]]];
const flattenedArray = nestedArray.reduce((acc, current) => {
return acc.concat(Array.isArray(current) ? flattenArray(current) : current);
}, []);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
这些方法都能够将嵌套的数组扁平化,但使用时需要根据具体情况选择最适合的方法。其中,递归方式对于嵌套层数较深的数组可能会有性能上的影响,而 `Array.prototype.flat()` 方法和 `Array.prototype.reduce()` 方法则是较为简洁高效的处理方式
数组扁平化的方法
猜你喜欢
转载自blog.csdn.net/kuang_nu/article/details/133211910
今日推荐
周排行