![](/img/trans.png)
[英]Easy way to turn JavaScript array into comma AND Quotation Marks separated string list?
[英]Easy way to turn JavaScript array into comma-separated list?
我在 JavaScript 中有一个一维字符串数组,我想将其转换为以逗号分隔的列表。 花园品种 JavaScript(或 jQuery)中是否有一种简单的方法可以将其转换为以逗号分隔的列表? (如果这是唯一的方法,我知道如何遍历数组并通过连接自己构建字符串。)
var arr = ["Zero", "One", "Two"]; document.write(arr.join(", "));
实际上, toString()
实现默认使用逗号进行连接:
var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto
我不知道这是否是 JS 规范规定的,但这就是最多几乎所有的浏览器似乎都在做。
或者(更有效地):
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 方法在调用时会返回您需要的内容 - 逗号分隔的列表。
简单数组
let simpleArray = [1,2,3,4] let commaSeperated = simpleArray.join(","); console.log(commaSeperated);
具有以逗号分隔的特定属性的对象数组。
let arrayOfObjects = [ { id : 1, name : "Name 1", address : "Address 1" }, { id : 2, name : "Name 2", address : "Address 2" }, { id : 3, name : "Name 3", address : "Address 3" }] let names = arrayOfObjects.map(x => x.name).join(", "); console.log(names);
结果
Name 1, Name 2, Name 3
如果您需要在最后两项之间使用“和”而不是“,”,您可以这样做:
function arrayToList(array){
return array
.join(", ")
.replace(/, ((?:.(?!, ))+)$/, ' and $1');
}
这是一个将二维数组或列数组转换为正确转义的 CSV 字符串的实现。 这些函数不检查有效的字符串/数字输入或列计数(确保您的数组一开始就有效)。 单元格可以包含逗号和引号!
这是一个用于解码 CSV 字符串的脚本。
这是我用于编码 CSV 字符串的脚本:
// Example
var csv = new csvWriter();
csv.del = '\t';
csv.enc = "'";
var nullVar;
var testStr = "The comma (,) pipe (|) single quote (') double quote (\") and tab (\t) are commonly used to tabulate data in plain-text formats.";
var testArr = [
false,
0,
nullVar,
// undefinedVar,
'',
{key:'value'},
];
console.log(csv.escapeCol(testStr));
console.log(csv.arrayToRow(testArr));
console.log(csv.arrayToCSV([testArr, testArr, testArr]));
/**
* Class for creating csv strings
* Handles multiple data types
* Objects are cast to Strings
**/
function csvWriter(del, enc) {
this.del = del || ','; // CSV Delimiter
this.enc = enc || '"'; // CSV Enclosure
// Convert Object to CSV column
this.escapeCol = function (col) {
if(isNaN(col)) {
// is not boolean or numeric
if (!col) {
// is null or undefined
col = '';
} else {
// is string or object
col = String(col);
if (col.length > 0) {
// use regex to test for del, enc, \r or \n
// if(new RegExp( '[' + this.del + this.enc + '\r\n]' ).test(col)) {
// escape inline enclosure
col = col.split( this.enc ).join( this.enc + this.enc );
// wrap with enclosure
col = this.enc + col + this.enc;
}
}
}
return col;
};
// Convert an Array of columns into an escaped CSV row
this.arrayToRow = function (arr) {
var arr2 = arr.slice(0);
var i, ii = arr2.length;
for(i = 0; i < ii; i++) {
arr2[i] = this.escapeCol(arr2[i]);
}
return arr2.join(this.del);
};
// Convert a two-dimensional Array into an escaped multi-row CSV
this.arrayToCSV = function (arr) {
var arr2 = arr.slice(0);
var i, ii = arr2.length;
for(i = 0; i < ii; i++) {
arr2[i] = this.arrayToRow(arr2[i]);
}
return arr2.join("\r\n");
};
}
我认为应该这样做:
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(',');
基本上它所做的只是检查字符串是否包含逗号或引号。 如果是这样,那么它将所有引号加倍,并将引号放在末尾。 然后它用逗号连接每个部分。
有很多方法可以将数组转换为逗号分隔的列表
来自MDN
join() 方法将数组(或类似数组的对象)的所有元素连接成一个字符串。
编码
var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");
var arr = ["this", "is", "a", "comma", "separated", "list"]; arr = arr.join(","); console.log(arr);
来自MDN
toString() 方法返回一个表示指定数组及其元素的字符串。
编码
var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();
var arr = ["this", "is", "a", "comma", "separated", "list"]; arr = arr.toString(); console.log(arr);
[]+或+[]会将其转换为字符串
([]+[] === [].toString())
将输出真
console.log([]+[] === [].toString());
var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;
var arr = ["this", "is", "a", "comma", "separated", "list"]; arr = []+arr; console.log(arr);
var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];
var arr = ["this", "is", "a", "comma", "separated", "list"]; arr = arr + []; console.log(arr);
使用内置的Array.toString
方法
var arr = ['one', 'two', 'three'];
arr.toString(); // 'one,two,three'
如果该值为null
或undefined
等,我通常会发现自己需要一些也跳过该值的东西。
所以这是适合我的解决方案:
// 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'
。 这就是为什么我更喜欢这个解决方案。
const arr = [1, 2, 3];
console.log(`${arr}`)
Papa Parse处理值和其他极端情况中的逗号。
(Node 的Baby Parse已被弃用 - 您现在可以在浏览器和 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"
我喜欢https://jsfiddle.net/rwone/qJUh2/上的解决方案,因为它在逗号后添加了空格:
array = ["test","test2","test3"]
array = array.toString();
array = array.replace(/,/g, ", ");
alert(array);
或者,正如@StackOverflaw 在评论中所建议的那样:
array.join(', ');
从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 和其他浏览器不兼容。
在这里,您可以使用任何字符分隔,并且可以仅使用 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";
使用 join 函数的初始答案是理想的。 要考虑的一件事是字符串的最终用途。
对于在某些最终文本显示中使用:
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"
当然,这一切都取决于最终用途。 只要牢记数据源和使用,一切都会好起来的。
你想用“和”结束它吗?
针对这种情况,我创建了一个 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
var arr = ["Pro1", "Pro2", "Pro3"];
console.log(arr.join());// Pro1,Pro2,Pro3
console.log(arr.join(', '));// Pro1, Pro2, Pro3
var array = ["Zero", "One", "Two"];
var s = array + [];
console.log(s); // => Zero,One,Two
此解决方案还删除了诸如" "
类的值:
const result = ['', null, 'foo', ' ', undefined, 'bar'].filter(el => {
return Boolean(el) && el.trim() !== '';
}).join(', ');
console.log(result); // => foo, bar
包含分隔符(逗号)的字符串的安全方法
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\\""
如果您有一个对象数组,但想要来自 object 上的一个属性的逗号分隔字符串。
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.