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

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

    Since all the answers allow NaN to be included, I thought I'd add that if you want to quickly cast an array of mixed values to numbers you can do.

    var a = "1,2,3,4,foo,bar";
    
    var b = a.split(',');
    
    var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.
    
    // or b.map(_=>_||0) if you know your array is just numbers but may include NaN.
    

提交回复
热议问题