我有一个JavaScript中的一维字符串数组,我想把它转换成一个逗号分隔的列表。在普通JavaScript(或jQuery)中是否有一种简单的方法将其转换为逗号分隔的列表?(我知道如何通过数组迭代,并通过连接自己构建字符串,如果这是唯一的方法。)
当前回答
你想以"and"结尾吗?
对于这种情况,我创建了一个npm模块。
试试arrford:
使用
const arrford = require('arrford');
arrford(['run', 'climb', 'jump!']);
//=> 'run, climb, and jump!'
arrford(['run', 'climb', 'jump!'], false);
//=> 'run, climb and jump!'
arrford(['run', 'climb!']);
//=> 'run and climb!'
arrford(['run!']);
//=> 'run!'
安装
npm install --save arrford
阅读更多
https://github.com/dawsonbotsford/arrford
自己试试吧
主音链接
其他回答
我通常发现自己需要一些东西,如果该值为空或未定义,也会跳过该值,等等。
下面是我的解决方案:
// 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'。这就是为什么我更喜欢这个解决方案。
从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。toString方法
var arr = ['one', 'two', 'three'];
arr.toString(); // 'one,two,three'
Array.toString()上的MDN
实际上,toString()实现默认使用逗号进行连接:
var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto
我不知道这是否是JS规范的要求,但这是几乎所有浏览器都在做的事情。
如果你需要用“and”代替“”,在最后两项之间,你可以这样做:
function arrayToList(array){
return array
.join(", ")
.replace(/, ((?:.(?!, ))+)$/, ' and $1');
}