You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用forEach方法扁平化数组返回空数组,问题出在哪里?

问题出在concat的特性上!

嘿,你踩了一个数组方法的常见小坑——concat() 不会修改原数组,它只会返回一个拼接后的全新数组。你当前的代码里只是调用了result.concat(element),但完全没把这个新生成的数组赋值回result,所以最初的空数组result根本没被更新,最后输出当然还是[]啦。

两种简单的修复方案:

1. 把concat的结果重新赋值给result

只需要修改forEach回调里的逻辑,把拼接后的新数组存回result:

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];
arrays.forEach((element) => {
  result = result.concat(element); // 关键:将新数组赋值回result
});
console.log(result); // 输出:[1, 2, 3, 4, 5, 6]

2. 改用push+扩展运算符(更高效)

如果只是扁平化一层嵌套的数组,用push(...element)直接把子数组的元素展开后添加到result里,既直观又避免了每次创建新数组的开销:

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];
arrays.forEach((element) => {
  result.push(...element); // 扩展运算符把子数组元素逐个push进去
});
console.log(result); // 输出:[1, 2, 3, 4, 5, 6]

额外加餐:深层扁平化的实现

如果你的数组是多层嵌套的(比如[[1, [2, [3]]], 4]),可以给forEach加上递归逻辑来处理:

function flattenDeep(arr) {
  let result = [];
  arr.forEach(element => {
    // 判断当前元素是不是数组,是的话递归处理
    if (Array.isArray(element)) {
      result = result.concat(flattenDeep(element));
    } else {
      result.push(element);
    }
  });
  return result;
}

let nestedArrays = [[1, [2, [3]]], [4, 5], [6]];
console.log(flattenDeep(nestedArrays)); // 输出:[1, 2, 3, 4, 5, 6]

内容的提问来源于stack exchange,提问作者cham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:56:31