在 JavaScript 中展平数组。
javascriptweb developmentobject oriented programming更新于 2025/10/9 1:16:17
我们需要编写一个 JavaScript 数组函数,该函数接受一个嵌套数组并返回一个 包含数组中所有元素的数组,没有任何嵌套。
例如 −
//如果输入为: const arr = [[1, 2, 3], [4, 5], [6]]; //则输出应为: const output = [1, 2, 3, 4, 5, 6];
因此,让我们编写该函数代码 −
方法一:使用递归
这里我们将循环遍历原始嵌套数组,并递归地将嵌套元素元素推送到新数组中。
示例
const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function(){
let res = [];
for(let i = 0; i < this.length; i++){
if(Array.isArray(this[i])){
res.push(...this[i].flatten());
} else {
res.push(this[i]);
};
};
return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());
方法 2:使用 Arrray.prototype.reduce()
这里我们将使用 reduce() 方法构造一个像这样的新数组 −
示例
const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function(){
return this.reduce((acc, val) => {
return acc.concat(...val);
}, []);
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());
输出
两种方法的控制台输出均为 −
[ 1, 2, 3, 4, 5, 6 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

