如何在JavaScript中将数组转换为逗号分隔的字符串 [英] How to convert array into comma separated string in javascript
问题描述
我有一个数组
a.value = [a,b,c,d,e,f]
如何转换为像
a.value = "a,b,c,d,e,f"
感谢所有帮助.
推荐答案
方法array.toString()
实际上会调用array.join()
,这将导致字符串以逗号连接. 参考
The method array.toString()
actually calls array.join()
which result in a string concatenated by commas. ref
var array = ['a','b','c','d','e','f'];
document.write(array.toString()); // "a,b,c,d,e,f"
此外,您可以通过使javascript将Array
强制转换为string
来隐式调用Array.toString()
,例如:
Also, you can implicitly call Array.toString()
by making javascript coerce the Array
to an string
, like:
//will implicitly call array.toString()
str = ""+array;
str = `${array}`;
Array.prototype.join()
join()方法将数组的所有元素连接到字符串中.
Array.prototype.join()
The join() method joins all elements of an array into a string.
它接受separator
作为参数,但是默认值已经是逗号,
It accepts a separator
as argument, but the default is already a comma ,
str = arr.join([separator = ','])
示例:
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'
注意:
如果数组的任何元素未定义或为null,则将其视为空字符串.
If any element of the array is undefined or null , it is treated as an empty string.
浏览器支持:
从IE 5.5(1999〜2000)开始,今天几乎所有地方都可以使用它.
Browser support:
It is available pretty much everywhere today, since IE 5.5 (1999~2000).
- ECMA Specification
- Mozilla
- MSDN
这篇关于如何在JavaScript中将数组转换为逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!