[英]Array to more than one string
I have a JavaScript array: 我有一个JavaScript数组:
cities = ["LA", "NYC", "Riyadh", "Frankfurt"]
The cities.toString()
function will give me cities.toString()
函数会给我
"LA, NYC, Riyadh, Frankfurt"
How do I get 如何得到
"LA", "NYC", "Riyadh", "Frankfurt"
The simplest way I can think of is to use JSON.stringify
and drop the first and last characters with slice
, like this 我能想到的最简单的方法是使用
JSON.stringify
与下降的第一和最后一个字符slice
,这样
var cities = ["LA", "NYC", "Riyadh", "Frankfurt"]
console.log(JSON.stringify(cities).slice(1, -1));
// "LA","NYC","Riyadh","Frankfurt"
If you want it, exactly like you mentioned in your answer, use map
function to generate new Strings surrounded by double quotes and finally join them with ,
like this 如果您想要的话,就像您在答案中提到的那样,请使用
map
函数生成新的用双引号引起来的Strings,最后将它们与结合起来,
就像这样
console.log(cities.map(function (currentCity) {
return '"' + currentCity + '"';
}).join(', '));
// "LA", "NYC", "Riyadh", "Frankfurt"
If your actual strings will not have any ,
in them, then you can chain the split
and join
calls, like this 如果您的实际字符串将不会有任何
,
在其中,那么你可以链上的split
和join
通话,这样
console.log(JSON.stringify(cities).slice(1, -1).split(",").join(", "));
// "LA", "NYC", "Riyadh", "Frankfurt"
You can use join function of array to join the array elements using any separator like: 您可以使用array的join函数通过任何分隔符将array元素连接起来,例如:
var result = '"' + cities.join('", "') + '"' ;
Check the working demo fiddle 检查工作演示小提琴
If you want to change an array into a string, there's array.join
. 如果要将数组更改为字符串,请使用
array.join
。 It works well with whatever delimiter you want to use: 它可以与您要使用的任何定界符一起很好地工作:
var array = ["LA", "NYC", "Riyadh", "Frankfurt"];
var string = '"' + array.join('", "') + '"';
// Result: "LA", "NYC", "Riyadh", "Frankfurt"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.