我有一个JavaScript中的一维字符串数组,我想把它转换成一个逗号分隔的列表。在普通JavaScript(或jQuery)中是否有一种简单的方法将其转换为逗号分隔的列表?(我知道如何通过数组迭代,并通过连接自己构建字符串,如果这是唯一的方法。)
当前回答
该解决方案还删除了诸如“”这样的值:
const result = ['', null, 'foo', ' ', undefined, 'bar'].filter(el => {
return Boolean(el) && el.trim() !== '';
}).join(', ');
console.log(result); // => foo, bar
其他回答
实际上,toString()实现默认使用逗号进行连接:
var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto
我不知道这是否是JS规范的要求,但这是几乎所有浏览器都在做的事情。
从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和其他浏览器不兼容。
在这里,您可以使用任何char进行分离,也可以仅使用foreach获取任何属性列表
let taskIds: string = '';
this.checkedTaskList.forEach(res => {
taskIds = taskIds + res.taskId.toString() + ','
});
if (taskIds) {
taskIds.substring(0, taskIds.length - 1),**
}
或者(更有效地):
var arr = new Array(3); arr[0] = "Zero"; arr[1] = "One"; arr[2] = "Two"; document.write(arr); // same as document.write(arr.toString()) in this context
当调用数组的toString方法时,返回的正是您所需要的—逗号分隔的列表。
取初始代码:
var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";
使用连接函数的初始答案是理想的。需要考虑的一件事是字符串的最终用途。
用于某些最终文本显示:
arr.join(",")
=> "Zero,One,Two"
用于在URL中以(有点)RESTful方式传递多个值:
arr.join("|")
=> "Zero|One|Two"
var url = 'http://www.yoursitehere.com/do/something/to/' + arr.join("|");
=> "http://www.yoursitehere.com/do/something/to/Zero|One|Two"
当然,这完全取决于最终的用途。只要记住数据源和使用方法,一切都将是正确的。