将JavaScript数组转换为逗号分隔列表的简单方法?

我有一个一维的JavaScript字符串数组,我想将其转换为以逗号分隔的列表。是否可以使用多种花园的JavaScript(或jQuery)将其转换为以逗号分隔的列表的简单方法?(如果这是唯一的方法,我知道如何遍历数组并自己通过串联构建字符串。)

神无小胖2020/04/03 11:35:58

有很多方法可以将数组转换为逗号分隔的列表

1.使用array#join

MDN

join()方法将数组(或类似数组的对象)的所有元素连接到字符串中。

代码

var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");

片段

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr.join(",");
console.log(arr);

2.使用array#toString

MDN

toString()方法返回一个字符串,该字符串表示指定的数组及其元素。

代码

var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();

片段

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr.toString();
console.log(arr);

3.在数组前添加[] +或在数组后添加+ []

[] ++ []将其转换成字符串

证明

([]+[] === [].toString())

将输出true

console.log([]+[] === [].toString());

var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;

片段

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = []+arr;
console.log(arr);

var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr + [];
console.log(arr);

古一2020/04/03 11:35:58

实际上,toString()默认情况下,该实现会使用逗号进行联接:

var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto

我不知道这是否由JS规范强制执行,但这是什么 几乎所有浏览器似乎都在这样做。

阿飞2020/04/03 11:35:58

或者(更有效地):

var arr = new Array(3);
arr [0] =“零”;
arr [1] =“一个”;
arr [2] =“两个”;

document.write(arr); //在这种情况下与document.write(arr.toString())相同

调用时,数组的toString方法将完全返回所需的内容-逗号分隔的列表。

神无前端2020/04/03 11:35:57

所述Array.prototype.join()方法:

var arr = ["Zero", "One", "Two"];

document.write(arr.join(", "));