我有一个JavaScript中的一维字符串数组,我想把它转换成一个逗号分隔的列表。在普通JavaScript(或jQuery)中是否有一种简单的方法将其转换为逗号分隔的列表?(我知道如何通过数组迭代,并通过连接自己构建字符串,如果这是唯一的方法。)
当前回答
使用内置的Array。toString方法
var arr = ['one', 'two', 'three'];
arr.toString(); // 'one,two,three'
Array.toString()上的MDN
其他回答
从Chrome 72开始,可以使用Intl。ListFormat:
const vehicles = ['Motorcycle', 'Bus', 'Car']; const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); console.log(formatter.format(vehicles)); // expected output: "Motorcycle, Bus, and Car" const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' }); console.log(formatter2.format(vehicles)); // expected output: "Motorcycle, Bus oder Car" const formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' }); console.log(formatter3.format(vehicles)); // expected output: "Motorcycle Bus Car"
请注意,这种方法还处于非常早期的阶段,所以在发布这个答案的日期,预计与旧版本的Chrome和其他浏览器不兼容。
如果你有一个对象数组,但想要一个逗号分隔的字符串从对象上的一个属性。
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'
该解决方案还删除了诸如“”这样的值:
const result = ['', null, 'foo', ' ', undefined, 'bar'].filter(el => {
return Boolean(el) && el.trim() !== '';
}).join(', ');
console.log(result); // => foo, bar
Array.prototype.join()方法:
var arr = [" 0 ", " 1 ", " 2 "]; document . write(加勒比海盗。加入(","));
const arr = [1, 2, 3];
console.log(`${arr}`)