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

如何在JavaScript中将数组转为字符串并保留元素两侧双引号

JavaScript数组转带双引号元素的字符串实现方法

最简实现(无特殊字符场景)

如果数组元素本身不包含双引号、换行等特殊字符,可以直接用map包裹元素后拼接:

const arr = ["hello", "there"];
const res = arr.map(item => `"${item}"`).join(', ');
// 输出结果:"hello", "there"

兼容特殊字符场景

如果元素可能包含双引号等需要转义的字符,用JSON.stringify处理单个元素更稳妥,会自动完成转义:

const arr = ['hello "world"', 'there'];
const res = arr.map(item => JSON.stringify(item)).join(', ');
// 输出结果:"hello \"world\"", "there"

其他可行写法

你之前的join写法只需要补全首尾的双引号即可,看到的反斜杠是调试工具的转义显示,并非字符串实际内容:

const arr = ["hello", "there"];
const res = '"' + arr.join('", "') + '"';
// 输出结果:"hello", "there"

也可以直接对整个数组做JSON.stringify后去掉首尾方括号:

const arr = ["hello", "there"];
const res = JSON.stringify(arr).slice(1, -1).replace(/","/g, '", "');
// 输出结果:"hello", "there"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:48:03