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

如何让flat()处理空嵌套数组时返回对应数量的undefined?

解决方法

你可以先把每个空数组替换成包含undefined的单元素数组,再调用flat(),这样就能得到你想要的结果:

const arr = [[], [], []];
const result = arr.map(subArr => subArr.length === 0 ? [undefined] : subArr).flat();
console.log(result); // [undefined, undefined, undefined]

或者更简洁的写法,利用空数组在布尔判断中为false的特性:

const arr = [[], [], []];
const result = arr.map(subArr => subArr || [undefined]).flat();
console.log(result); // [undefined, undefined, undefined]

这种处理方式不会影响原本包含undefined或其他元素的子数组,比如你提到的[[undefined, 4], [4]]经过同样逻辑处理后,结果依然是[undefined, 4, 4],完全适配你的统计需求。

内容的提问来源于stack exchange,提问作者sir-haver

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:55:25