我有一个JavaScript中的一维字符串数组,我想把它转换成一个逗号分隔的列表。在普通JavaScript(或jQuery)中是否有一种简单的方法将其转换为逗号分隔的列表?(我知道如何通过数组迭代,并通过连接自己构建字符串,如果这是唯一的方法。)
当前回答
const arr = [1, 2, 3];
console.log(`${arr}`)
其他回答
或者(更有效地):
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方法时,返回的正是您所需要的—逗号分隔的列表。
Papa Parse处理值中的逗号和其他边缘情况。
(Baby Parse for Node已弃用-你现在可以在浏览器和Node中使用Papa Parse。)
如。(节点)
const csvParser = require('papaparse'); // previously you might have used babyparse
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;
1,,“a,b”
从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和其他浏览器不兼容。
Array.prototype.join()方法:
var arr = [" 0 ", " 1 ", " 2 "]; document . write(加勒比海盗。加入(","));
包含分隔符(逗号)的字符串的安全方法
let arr = ["Hello, there", "How's there", 'the "best"']
let csv = arr.map(e => JSON.stringify(e)).join(",")
console.log(csv)
结果
"Hello, there","How's there","the \\"best\\""