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

后端 未结 15 1417
温柔的废话
温柔的废话 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 03:21

    Note that the following:

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

    will alert 1

    0 讨论(0)
  • 2020-11-22 03:21
    let str = "January,February,March,April,May,June,July,August,September,October,November,December"
    
    let arr = str.split(',');
    

    it will result:

    ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    

    and if you want to convert following to:

    ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    

    this:

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

    use:

    str = arr.join(',')
    
    0 讨论(0)
  • 2020-11-22 03:22

    Here is a function that will convert a string to an array, even if there is only one item in the list (no separator character):

    function listToAray(fullString, separator) {
      var fullArray = [];
    
      if (fullString !== undefined) {
        if (fullString.indexOf(separator) == -1) {
          fullAray.push(fullString);
        } else {
          fullArray = fullString.split(separator);
        }
      }
    
      return fullArray;
    }
    

    Use it like this:

    var myString = 'alpha,bravo,charlie,delta';
    var myArray = listToArray(myString, ',');
    myArray[2]; // charlie
    
    var yourString = 'echo';
    var yourArray = listToArray(yourString, ',');
    yourArray[0]; // echo
    

    I created this function because split throws out an error if there isn't any separator character in the string (only one item).

    0 讨论(0)
提交回复
热议问题