我有一个逗号分隔的字符串,我想把它转换成一个数组,这样我就可以遍历它。

有什么内置的功能吗?

例如,我有这个字符串

var str = "January,February,March,April,May,June,July,August,September,October,November,December";

现在我想用逗号将其拆分,然后将其存储在数组中。


当前回答

将逗号分隔的字符串传递到此函数,它将返回一个数组,如果找不到逗号分隔字符串,则返回null。

function splitTheString(CommaSepStr) {
    var ResultArray = null;

    // Check if the string is null or so.
    if (CommaSepStr!= null) {

        var SplitChars = ',';

        // Check if the string has comma of not will go to else
        if (CommaSepStr.indexOf(SplitChars) >= 0) {
            ResultArray = CommaSepStr.split(SplitChars);

        }
        else {

            // The string has only one value, and we can also check
            // the length of the string or time and cross-check too.
            ResultArray = [CommaSepStr];
        }
    }
    return ResultArray;
}

其他回答

如果你的目标是整数,比如1,2,3,4,5,请注意。如果要在拆分字符串后将数组元素用作整数而不是字符串,请考虑将它们转换为整数。

var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");

添加这样的循环,

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

将返回一个包含整数而非字符串的数组。

返回函数

var array = (new Function("return [" + str+ "];")());

其接受字符串和对象字符串:

var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle公司https://jsfiddle.net/7ne9L4Lj/1/

将逗号分隔的字符串传递到此函数,它将返回一个数组,如果找不到逗号分隔字符串,则返回null。

function splitTheString(CommaSepStr) {
    var ResultArray = null;

    // Check if the string is null or so.
    if (CommaSepStr!= null) {

        var SplitChars = ',';

        // Check if the string has comma of not will go to else
        if (CommaSepStr.indexOf(SplitChars) >= 0) {
            ResultArray = CommaSepStr.split(SplitChars);

        }
        else {

            // The string has only one value, and we can also check
            // the length of the string or time and cross-check too.
            ResultArray = [CommaSepStr];
        }
    }
    return ResultArray;
}

最简单的方法:

let myStr = '1, 2, 3, 4, 5, 7, 8';

const stringToArr = (myStr) => {
    return myStr.split(',').map(x => x.trim());
};

一个很好的解决方案:

let obj = ['A','B','C']

obj.map((c) => { return c. }).join(', ')