我有一个JavaScript数组:
cities = ["LA", "NYC", "Riyadh", "Frankfurt"]
cities.toString()
函数会给我
"LA, NYC, Riyadh, Frankfurt"
我如何获得
"LA", "NYC", "Riyadh", "Frankfurt"
答案 0 :(得分:3)
我能想到的最简单的方法是使用JSON.stringify
并使用slice
删除第一个和最后一个字符,就像这样
var cities = ["LA", "NYC", "Riyadh", "Frankfurt"]
console.log(JSON.stringify(cities).slice(1, -1));
// "LA","NYC","Riyadh","Frankfurt"
如果你想要它,就像你在答案中提到的那样,使用map
函数生成用双引号括起来的新字符串,最后用这样的,
加入它们
console.log(cities.map(function (currentCity) {
return '"' + currentCity + '"';
}).join(', '));
// "LA", "NYC", "Riyadh", "Frankfurt"
如果您的实际字符串中没有,
,那么您可以链接split
和join
来电,就像这样
console.log(JSON.stringify(cities).slice(1, -1).split(",").join(", "));
// "LA", "NYC", "Riyadh", "Frankfurt"
答案 1 :(得分:1)
答案 2 :(得分:0)
如果要将数组更改为字符串,则为array.join
。它适用于您想要使用的任何分隔符:
var array = ["LA", "NYC", "Riyadh", "Frankfurt"];
var string = '"' + array.join('", "') + '"';
// Result: "LA", "NYC", "Riyadh", "Frankfurt"