假设我有
const colors = ['red', 'yellow', 'pink']
如何将此数组转换为字符串:
""red", "yellow","pink""
I have try:colors.map(id => "'" + id + "'").join(', ')
,但这给出:"'red', 'yellow', 'pink'"
你可以试试这个
const colors = ['red', 'yellow', 'pink'];
let result = colors.map(c => `"${c}"`).join(',');
console.log(result);
您可以使用join和replace来获得期望的结果
const colors = ["red", "yellow", "pink"];
let result = colors.join(", ").replace(/[a-z]+/gi, `"$&"`);
console.log(result);
你可以用单引号括住双引号,或者在双引号里面转义双引号,或者使用ES6+模板字面量(2015年引入):
const colors = ['red', 'yellow', 'pink']
console.log('"' + colors.map((str) => '"' + str + '"').join(", " + '"'));
console.log(""" + colors.map((str) => """ + str + """).join(", ") + """);
console.log('"' + colors.map((str) => `"${str}"`).join(", ") + '"');