Javascript 通过逗号和空格连接数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5080165/
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:33:48  来源:igfitidea点击:

Join an array by a comma and a space

javascriptarraysstringtostring

提问by Myles Gray

I have an array that I want converted to a comma delimited string. Array.toString()works, but if I have a rather large array it won't wrap because there are no spaces after the commas:

我有一个要转换为逗号分隔字符串的数组。Array.toString()有效,但如果我有一个相当大的数组,它不会换行,因为逗号后没有空格:

document.body.innerHTML = ['css','html','xhtml','html5','css3','javascript','jquery','lesscss','arrays','wordpress','facebook','fbml','table','.htaccess','php','c','.net','c#','java'].toString();
// css,html,xhtml,html5,css3,javascript,jquery,lesscss,arrays,wordpress,facebook,fbml,table,.htaccess,php,c,.net,c#,java

How can I have spaces after the commas in order to allow line/word wrapping?

如何在逗号后有空格以允许换行/自动换行?

Example output:

示例输出:

css, html, xhtml, html5, css3, javascript, jquery, lesscss, arrays, wordpress, facebook, fbml, table, .htaccess, php, c, .net, c#, java

回答by Nick Craver

In JavaScript there's a .join()method on arrays to get a string, which you can provide the delimiter to. In your case it'd look like this:

在 JavaScript 中有一个.join()数组方法可以获取字符串,您可以为其提供分隔符。在你的情况下,它看起来像这样:

var myArray = ['css','html','xhtml','html5','css3','javascript','jquery','lesscss','arrays','wordpress','facebook','fbml','table','.htaccess','php','c','.net','c#','java'];
var myString = myArray.join(', ');

You can test it out here

你可以在这里测试

回答by adarshr

Use array.join(", ");and it should work

使用array.join(", ");它应该可以工作

回答by John xyz

 string.Join(", ", new string[] { "css", "html", "xhtml", ..etc });

This prints the items with a comma and a space

这将打印带有逗号和空格的项目

[edit] I'm sorry, did not see it was for javascript. My code is c# :)

[编辑] 对不起,没有看到它是针对 javascript 的。我的代码是 c# :)