How to convert comma separated string into numeric array in javascript

后端 未结 9 1759
粉色の甜心
粉色の甜心 2021-02-05 02:06

I have a one-dimensional array of integer in JavaScript that I\'d like to add data from comma separated string, Is there a simple way to do this?

e.g : var strVale

9条回答
  •  深忆病人
    2021-02-05 02:52

    You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.

    arr = strVale.split(',');
    

    Live Demo

    var strVale = "130,235,342,124";
    arr = strVale.split(',');
    for(i=0; i < arr.length; i++)
        console.log(arr[i] + " * 2 = " + (arr[i])*2);
    

    Output

    130 * 2 = 260
    235 * 2 = 470
    342 * 2 = 684
    124 * 2 = 248
    

    Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.

    var strVale = "130,235,342,124";
    var strArr = strVale.split(',');
    var intArr = [];
    for(i=0; i < strArr.length; i++)
       intArr.push(parseInt(strArr[i]));
    

提交回复
热议问题