Join an array by a comma and a space

青春壹個敷衍的年華 提交于 2019-12-18 18:33:51

问题


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:

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

回答1:


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:

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




回答2:


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




回答3:


 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# :)



来源:https://stackoverflow.com/questions/5080165/join-an-array-by-a-comma-and-a-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!