How to convert a string of numbers to an array of numbers?

前端 未结 15 2061
死守一世寂寞
死守一世寂寞 2020-11-27 10:29

I have below string -

var a = \"1,2,3,4\";

when I do -

var b = a.split(\',\');

I get b as

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 10:48

    Map it to integers:

    a.split(',').map(function(i){
        return parseInt(i, 10);
    })
    

    map looks at every array item, passes it to the function provided and returns an array with the return values of that function. map isn't available in old browsers, but most libraries like jQuery or underscore include a cross-browser version.

    Or, if you prefer loops:

    var res = a.split(",");
    for (var i=0; i

提交回复
热议问题