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

前端 未结 15 2090
死守一世寂寞
死守一世寂寞 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

    My 2 cents for golfers:

    b="1,2,3,4".split`,`.map(x=>+x)
    

    backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(','). The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x (which is even shorter than the Number function (5 chars instead of 6)) is equivalent to :

    function(x){return parseInt(x,10)}// version from techfoobar
    (x)=>{return parseInt(x)}         // lambda are shorter and parseInt default is 10
    (x)=>{return +x}                  // diff. with parseInt in SO but + is better in this case
    x=>+x                             // no multiple args, just 1 function call
    

    I hope it is a bit more clear.

提交回复
热议问题