How can I convert a comma-separated string to an array?

后端 未结 15 1423
温柔的废话
温柔的废话 2020-11-22 02:37

I have a comma-separated string that I want to convert into an array, so I can loop through it.

Is there anything built-in to do this?

For example, I have this

15条回答
  •  温柔的废话
    2020-11-22 02:56

    Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

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

    Adding a loop like this,

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

    will return an array containing integers, and not strings.

提交回复
热议问题