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

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

    You can transform array of strings to array of numbers in one line:

    const arrayOfNumbers = arrayOfStrings.map(e => +e);
    
    0 讨论(0)
  • 2020-11-27 11:07

    You can use JSON.parse, adding brakets to format Array

    const a = "1,2,3,4";
    const myArray = JSON.parse(`[${a}]`)
    console.log(myArray)
    console.info('pos 2 = ',  myArray[2])

    0 讨论(0)
  • 2020-11-27 11:08

    One liner

    Array.from(a.split(','), Number)
    
    0 讨论(0)
提交回复
热议问题