How to convert comma separated string into numeric array in javascript

后端 未结 9 1782
粉色の甜心
粉色の甜心 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:55

    You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:

    var arr = [1,2,3],
        strVale = "130,235,342,124 ";
    var strings = strVale.split(",");
    for (var i=0; i

    Or, in one step, using Array map to convert them and applying them to one single push:

    arr.push.apply(arr, strVale.split(",").map(Number));
    

提交回复
热议问题