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

如何用ES6提取嵌套数组元素并转为逗号加空格字符串加入父数组

可以实现,以下是两种符合ES6规范的实现方案:

方案1:使用flatMap(ES2019支持,属于ES6迭代标准)

flatMap会先遍历数组执行映射逻辑,再自动将结果展平一级,代码最简洁:

const a1 = ['one', 'two', ['three', 'four']];
const a2 = a1.flatMap(item => Array.isArray(item) ? item.join(', ') : item);
// 输出结果:['one', 'two', 'three, four']

方案2:使用map+扩展运算符(兼容ES2015初始版本)

如果你的运行环境仅支持ES2015最初的规范,可以用这个版本:

const a1 = ['one', 'two', ['three', 'four']];
const a2 = [].concat(...a1.map(item => Array.isArray(item) ? item.join(', ') : item));
// 输出结果:['one', 'two', 'three, four']

两种方案的核心逻辑一致:遍历原数组时判断元素类型,如果是子数组就调用join(', ')拼接为逗号加空格分隔的字符串,普通元素直接返回,最终得到目标结构的数组。

内容的提问来源于stack exchange,提问作者R.H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:27:01