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

有什么内置的功能吗?

例如,我有这个字符串

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

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


当前回答

最简单的方法:

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

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

其他回答

请注意:

var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);

将提醒1

我有一个类似的问题,但更复杂的是,我需要将CSV文件转换为数组数组(每一行都是一个数组元素,其中包含一个以逗号分隔的项目数组)。

最简单的解决方案(我打赌更安全)是使用PapaParse,它有一个“无头”选项,可以将CSV文件转换为数组数组,而且它会自动检测到“,”作为分隔符。

另外,它是在Bower注册的,所以我只需要:

bower install papa-parse --save

然后在我的代码中使用它,如下所示:

var arrayOfArrays = Papa.parse(csvStringWithEnters), {header:false}).data;

我真的很喜欢。

一个很好的解决方案:

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

obj.map((c) => { return c. }).join(', ')
var array = string.split(',');

MDN引用,对于极限参数的可能意外行为非常有用。(提示:“a,b,c”.split(“,”,2)指向[“a”,“b”],而不是[“a,”b,c“]。)

将逗号分隔的字符串传递到此函数,它将返回一个数组,如果找不到逗号分隔字符串,则返回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;
}