我有一个JavaScript中的一维字符串数组,我想把它转换成一个逗号分隔的列表。在普通JavaScript(或jQuery)中是否有一种简单的方法将其转换为逗号分隔的列表?(我知道如何通过数组迭代,并通过连接自己构建字符串,如果这是唯一的方法。)


当前回答

如果你有一个对象数组,但想要一个逗号分隔的字符串从对象上的一个属性。

var arr = [
    { Id: 1, Name: 'Item 1' },
    { Id: 2, Name: 'Item 2' },
    { Id: 3, Name: 'Item 3' }
];
var result = arr.map(i => { return i.Name; }).join(', ');
console.log(result); // 'Item 1, Item 2, Item 3'

其他回答

Array.prototype.join()方法:

var arr = [" 0 ", " 1 ", " 2 "]; document . write(加勒比海盗。加入(","));

我通常发现自己需要一些东西,如果该值为空或未定义,也会跳过该值,等等。

下面是我的解决方案:

// Example 1
const arr1 = ['apple', null, 'banana', '', undefined, 'pear'];
const commaSeparated1 = arr1.filter(item => item).join(', ');
console.log(commaSeparated1); // 'apple, banana, pear'

// Example 2
const arr2 = [null, 'apple'];
const commaSeparated2 = arr2.filter(item => item).join(', ');
console.log(commaSeparated2); // 'apple'

如果我的数组看起来像第二个例子中的数组,大多数解都会返回',apple'。这就是为什么我更喜欢这个解决方案。

如果你有一个对象数组,但想要一个逗号分隔的字符串从对象上的一个属性。

var arr = [
    { Id: 1, Name: 'Item 1' },
    { Id: 2, Name: 'Item 2' },
    { Id: 3, Name: 'Item 3' }
];
var result = arr.map(i => { return i.Name; }).join(', ');
console.log(result); // 'Item 1, Item 2, Item 3'

我认为这应该做到:

var arr = ['contains,comma', 3.14, 'contains"quote', "more'quotes"]
var item, i;
var line = [];

for (i = 0; i < arr.length; ++i) {
    item = arr[i];
    if (item.indexOf && (item.indexOf(',') !== -1 || item.indexOf('"') !== -1)) {
        item = '"' + item.replace(/"/g, '""') + '"';
    }
    line.push(item);
}

document.getElementById('out').innerHTML = line.join(',');

小提琴

基本上,它所做的就是检查字符串是否包含逗号或引号。如果是,那么它将所有的引号都翻倍,并在结尾加上引号。然后用逗号将每个部分连接起来。

使用内置的Array。toString方法

var arr = ['one', 'two', 'three'];
arr.toString();  // 'one,two,three'

Array.toString()上的MDN