将JavaScript数组转换成逗号分隔列表的简单方法?

时间:2022-09-02 00:21:50

I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)

我在JavaScript中有一个一维字符串数组,我想把它变成一个逗号分隔的列表。在普通的JavaScript(或jQuery)中,是否有一种简单的方法将其转换成逗号分隔的列表?(我知道如何遍历数组,如果这是唯一的方法,我可以通过连接自己构建字符串。)

14 个解决方案

#1


604  

The Array.prototype.join() method:

Array.prototype.join()方法:

var arr = ["Zero", "One", "Two"];

document.write(arr.join(", "));

#2


80  

Actually, the toString() implementation does a join with commas by default:

实际上,toString()实现在默认情况下使用逗号连接:

var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto

I don't know if this is mandated by the JS spec but this is what most pretty much all browsers seem to be doing.

我不知道JS规范是否规定了这一点,但几乎所有浏览器都是这么做的。

#3


28  

Or (more efficiently):

或(更有效):

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

The toString method of an array when called returns exactly what you need - comma-separated list.

数组的toString方法在被调用时返回您需要的-逗号分隔的列表。

#4


13  

Here's an implementation that converts a two-dimensional array or an array of columns into a properly escaped CSV string. The functions do not check for valid string/number input or column counts (ensure your array is valid to begin with). The cells can contain commas and quotes!

这是一个实现,它将二维数组或列数组转换为正确转义的CSV字符串。函数不检查有效的字符串/数字输入或列计数(确保数组一开始是有效的)。单元格可以包含逗号和引号!

Here's a script for decoding CSV strings.

这是一个解码CSV字符串的脚本。

Here's my script for encoding CSV strings:

这是我编码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");
    };
}

#5


10  

I think this should do it:

我认为这应该可以做到:

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(',');

fiddle

小提琴

Basically all it does is check if the string contains a comma or quote. If it does, then it doubles all the quotes, and puts quotes on the ends. Then it joins each of the parts with a comma.

基本上它所做的就是检查字符串是否包含逗号或引号。如果是这样,那么它就会使所有的引号都翻倍,并在末尾加上引号。然后用逗号将每个部分连接起来。

#6


6  

Use the built-in Array.toString method

使用内置的数组。toString方法

var arr = ['one', 'two', 'three'];
arr.toString();  // 'one,two,three'

MDN on Array.toString()

MDN Array.toString()

#7


3  

If you need to use " and " instead of ", " between the last two items you can do this:

如果你需要在最后两项中使用“and”而不是“”,你可以这样做:

function arrayToList(array){
  return array
    .join(", ")
    .replace(/, ((?:.(?!, ))+)$/, ' and $1');
}

#8


3  

I usually find myself needing something that also skips the value if that value is null or undefined, etc.

如果值为null或未定义,我通常会发现自己需要一些可以跳过该值的东西。

So here is the solution that works for me:

这就是我的解决方案:

// 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'

Most of the solutions here would return ', apple' if my array would look like the one in my second example. That's why I prefer this solution.

这里的大多数解决方案都会返回',apple'如果我的数组看起来像第二个例子中的那个。这就是我喜欢这个解决方案的原因。

#9


2  

There are many methods to convert an array to comma separated list

有许多方法可以将数组转换为逗号分隔的列表

1. Using array#join

From MDN

从MDN

The join() method joins all elements of an array (or an array-like object) into a string.

join()方法将数组的所有元素(或类似数组的对象)连接到一个字符串中。

The code

的代码

var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr.join(",");
console.log(arr);

2. Using array#toString

From MDN

从MDN

The toString() method returns a string representing the specified array and its elements.

toString()方法返回表示指定数组及其元素的字符串。

The code

的代码

var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr.toString();
console.log(arr);

3. Add []+ before array or +[] after an array

The []+ or +[] will convert it into a string

[]+或+[]将把它转换成字符串

Proof

([]+[] === [].toString())

will output true

将输出真正的

console.log([]+[] === [].toString());

var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = []+arr;
console.log(arr);

Also

var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr + [];
console.log(arr);

#10


1  

Taking the initial code:

在最初的代码:

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

The initial answer of using the join function is ideal. One thing to consider would be the ultimate use of the string.

使用join函数的初始答案是理想的。要考虑的一件事是绳子的最终用途。

For using in some end textual display:

用于终端文本显示:

arr.join(",")
=> "Zero,One,Two"

For using in a URL for passing multiple values through in a (somewhat) RESTful manner:

用于在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"

Of course, it all depends on the final use. Just keep the data source and use in mind and all will be right with the world.

当然,这一切都取决于最终的用途。只要保持数据来源和使用,一切都将是正确的。

#11


1  

Do you want to end it with an "and"?

你想以"and"结尾吗?

For this situation, I created an npm module.

对于这种情况,我创建了一个npm模块。

Try arrford:

试试arrford:


Usage

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!'


Install

npm install --save arrford


Read More

https://github.com/dawsonbotsford/arrford

https://github.com/dawsonbotsford/arrford


Try it yourself

Tonic link

主音链接

#12


0  

var arr = ["Pro1", "Pro2", "Pro3"];
console.log(arr.join());// Pro1,Pro2,Pro3
console.log(arr.join(', '));// Pro1, Pro2, Pro3

#13


0  

Papa Parse (browser based) handles commas in values and other edge cases. Use Baby Parse for Node.

Papa Parse(基于浏览器的)处理值和其他边缘情况中的逗号。对节点使用Baby Parse。

Eg. (node)

如。(节点)

const csvParser = require('babyparse');
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;

1,,"a,b"

1、“甲、乙”

#14


-1  

var array = ["Zero", "One", "Two"];
var s = array + [];
console.log(s); // => Zero,One,Two

#1


604  

The Array.prototype.join() method:

Array.prototype.join()方法:

var arr = ["Zero", "One", "Two"];

document.write(arr.join(", "));

#2


80  

Actually, the toString() implementation does a join with commas by default:

实际上,toString()实现在默认情况下使用逗号连接:

var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto

I don't know if this is mandated by the JS spec but this is what most pretty much all browsers seem to be doing.

我不知道JS规范是否规定了这一点,但几乎所有浏览器都是这么做的。

#3


28  

Or (more efficiently):

或(更有效):

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

The toString method of an array when called returns exactly what you need - comma-separated list.

数组的toString方法在被调用时返回您需要的-逗号分隔的列表。

#4


13  

Here's an implementation that converts a two-dimensional array or an array of columns into a properly escaped CSV string. The functions do not check for valid string/number input or column counts (ensure your array is valid to begin with). The cells can contain commas and quotes!

这是一个实现,它将二维数组或列数组转换为正确转义的CSV字符串。函数不检查有效的字符串/数字输入或列计数(确保数组一开始是有效的)。单元格可以包含逗号和引号!

Here's a script for decoding CSV strings.

这是一个解码CSV字符串的脚本。

Here's my script for encoding CSV strings:

这是我编码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");
    };
}

#5


10  

I think this should do it:

我认为这应该可以做到:

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(',');

fiddle

小提琴

Basically all it does is check if the string contains a comma or quote. If it does, then it doubles all the quotes, and puts quotes on the ends. Then it joins each of the parts with a comma.

基本上它所做的就是检查字符串是否包含逗号或引号。如果是这样,那么它就会使所有的引号都翻倍,并在末尾加上引号。然后用逗号将每个部分连接起来。

#6


6  

Use the built-in Array.toString method

使用内置的数组。toString方法

var arr = ['one', 'two', 'three'];
arr.toString();  // 'one,two,three'

MDN on Array.toString()

MDN Array.toString()

#7


3  

If you need to use " and " instead of ", " between the last two items you can do this:

如果你需要在最后两项中使用“and”而不是“”,你可以这样做:

function arrayToList(array){
  return array
    .join(", ")
    .replace(/, ((?:.(?!, ))+)$/, ' and $1');
}

#8


3  

I usually find myself needing something that also skips the value if that value is null or undefined, etc.

如果值为null或未定义,我通常会发现自己需要一些可以跳过该值的东西。

So here is the solution that works for me:

这就是我的解决方案:

// 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'

Most of the solutions here would return ', apple' if my array would look like the one in my second example. That's why I prefer this solution.

这里的大多数解决方案都会返回',apple'如果我的数组看起来像第二个例子中的那个。这就是我喜欢这个解决方案的原因。

#9


2  

There are many methods to convert an array to comma separated list

有许多方法可以将数组转换为逗号分隔的列表

1. Using array#join

From MDN

从MDN

The join() method joins all elements of an array (or an array-like object) into a string.

join()方法将数组的所有元素(或类似数组的对象)连接到一个字符串中。

The code

的代码

var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr.join(",");
console.log(arr);

2. Using array#toString

From MDN

从MDN

The toString() method returns a string representing the specified array and its elements.

toString()方法返回表示指定数组及其元素的字符串。

The code

的代码

var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr.toString();
console.log(arr);

3. Add []+ before array or +[] after an array

The []+ or +[] will convert it into a string

[]+或+[]将把它转换成字符串

Proof

([]+[] === [].toString())

will output true

将输出真正的

console.log([]+[] === [].toString());

var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;

Snippet

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = []+arr;
console.log(arr);

Also

var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];

var arr = ["this", "is", "a", "comma", "separated", "list"];
arr = arr + [];
console.log(arr);

#10


1  

Taking the initial code:

在最初的代码:

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

The initial answer of using the join function is ideal. One thing to consider would be the ultimate use of the string.

使用join函数的初始答案是理想的。要考虑的一件事是绳子的最终用途。

For using in some end textual display:

用于终端文本显示:

arr.join(",")
=> "Zero,One,Two"

For using in a URL for passing multiple values through in a (somewhat) RESTful manner:

用于在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"

Of course, it all depends on the final use. Just keep the data source and use in mind and all will be right with the world.

当然,这一切都取决于最终的用途。只要保持数据来源和使用,一切都将是正确的。

#11


1  

Do you want to end it with an "and"?

你想以"and"结尾吗?

For this situation, I created an npm module.

对于这种情况,我创建了一个npm模块。

Try arrford:

试试arrford:


Usage

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!'


Install

npm install --save arrford


Read More

https://github.com/dawsonbotsford/arrford

https://github.com/dawsonbotsford/arrford


Try it yourself

Tonic link

主音链接

#12


0  

var arr = ["Pro1", "Pro2", "Pro3"];
console.log(arr.join());// Pro1,Pro2,Pro3
console.log(arr.join(', '));// Pro1, Pro2, Pro3

#13


0  

Papa Parse (browser based) handles commas in values and other edge cases. Use Baby Parse for Node.

Papa Parse(基于浏览器的)处理值和其他边缘情况中的逗号。对节点使用Baby Parse。

Eg. (node)

如。(节点)

const csvParser = require('babyparse');
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;

1,,"a,b"

1、“甲、乙”

#14


-1  

var array = ["Zero", "One", "Two"];
var s = array + [];
console.log(s); // => Zero,One,Two