Javascript 如何在javascript中将数组转换为逗号分隔的字符串

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

How to convert array into comma separated string in javascript

javascriptarrays

提问by David

I have an array

我有一个数组

a.value = [a,b,c,d,e,f]

a.value = [a,b,c,d,e,f]

How can I convert to comma seperated string like

如何转换为逗号分隔的字符串,如

a.value = "a,b,c,d,e,f"

a.value = "a,b,c,d,e,f"

Thanks for all help.

感谢所有帮助。

回答by Vitim.us

The method array.toString()actually calls array.join()which result in a string concatenated by commas. ref

该方法array.toString()实际调用的array.join()结果是一个由逗号连接的字符串。参考

var array = ['a','b','c','d','e','f'];
document.write(array.toString()); // "a,b,c,d,e,f"

Also, you can implicitly call Array.toString()by making javascript coerce the Arrayto an string, like:

此外,您可以Array.toString()通过将 javascript 强制Array为 an来隐式调用string,例如:

//will implicitly call array.toString()
str = ""+array;
str = `${array}`;


Array.prototype.join()

Array.prototype.join()

The join()method joins all elements of an array into a string.

加入()方法连接到一个字符串数组的所有元素。

Arguments:

参数:

It accepts a separatoras argument, but the default is already a comma ,

它接受 aseparator作为参数,但默认值已经是逗号,

str = arr.join([separator = ','])

Examples:

例子:

var array = ['A', 'B', 'C'];
var myVar1 = array.join();      // 'A,B,C'
var myVar2 = array.join(', ');  // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join('');    // 'ABC'

Note:

笔记:

If any element of the array is undefined or null , it is treated as an empty string.

如果数组的任何元素是 undefined 或 null ,则将其视为空字符串。

Browser support:

浏览器支持:

It is available pretty much everywhere today, since IE 5.5 (1999~2000).

从 IE 5.5 (1999~2000) 开始,它现在几乎无处不在。

References

参考

回答by Renan

Use the joinmethodfrom the Array type.

使用Array 类型的join方法

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The joinmethod will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

join方法将返回一个字符串,它是所有数组元素的串联。它将使用您传递的第一个参数作为分隔符 - 如果您不使用,它将使用默认分隔符,即逗号。

回答by Aer0

You can simply use JavaScripts join()function for that. This would simply look like a.value.join(','). The output would be a string though.

您可以简单地使用 JavaScriptsjoin()函数。这看起来就像a.value.join(','). 虽然输出将是一个字符串。