如何在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
相关产品推荐
相关产品推荐

