Javascript 创建逗号分隔的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5166385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:54:05  来源:igfitidea点击:

Create comma-delimited string

javascript

提问by Urbycoz

I'm looking to find a neat way to create a comma-delimited string from an array. This is how I'm doing it now...

我正在寻找一种巧妙的方法来从数组创建逗号分隔的字符串。这就是我现在的做法...

for(i=0;i<10;i++)
{
   str = str + ',' + arr[i];
}
str=str.substring(1)
return str;

... but it feels a bit untidy.

……不过感觉有点乱。

回答by jAndy

Array.prototype.join()is what you're looking for:

Array.prototype.join()是你要找的:

arr.join(',');

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join



var arr = ['Hi', 'I', 'am', 'a', 'comma', 'separated', 'list'];

arr.join(',');  // === "Hi,I,am,a,comma,separated,list" 

回答by Oliver M Grech

you have to use

你必须使用

var joinedstr = myarray.join(',');

varjoinedstr = myarray.join(',');

回答by mbq

Use the join method:

使用join方法:

arr.join(',');

回答by Sachin Shanbhag

I think there is something like array.join(',')where arrayis your array variable instance.

我认为有类似的array.join(',')地方array是你的数组变量实例。

回答by Alex

Use the join function:

使用连接函数:

myarray.join(',');

myarray.join(',');