用逗号和空格连接数组

我有一个数组,我想转换为逗号分隔的字符串。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

如何在逗号后面加空格以允许行/字包装?

输出示例:

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

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

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

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

Had to put an # in front of every word, the .join() didn't work for the first one and had to do this :

var myString = '#'+ myArray.join(', ');

Try this way by the regex

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


let myString = arr.replace(/,[s]*/g, ", ");




console.log(myString);

I saw in a comment the question of how to make that without the .join() function.

Here is one tricky way:

const array_of_strings = ['css','html','xhtml','html5','css3','javascript','jquery','lesscss','arrays','wordpress','facebook','fbml','table','.htaccess','php','c','.net','c#','java']
const separator = ', '
const result = array_of_strings.reduce((accumulator, currentValue) => accumulator + separator + currentValue);
console.log(result)