How to convert comma separated string into numeric array in javascript

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

    All of the given answers so far create a possibly unexpected result for a string like ",1,0,-1,, ,,2":

    ",1,0,-1,,  ,,2".split(",").map(Number).filter(x => !isNaN(x))
    // [0, 1, 0, -1, 0, 0, 0, 2]
    

    To solve this, I've come up with the following fix:

    ",1,0,-1,,  ,,2".split(',').filter(x => x.trim() !== "").map(Number).filter(x => !isNaN(x))
    // [1, 0, -1, 2]
    

    Please note that due to

    isNaN("") // false!
    

    and

    isNaN(" ") // false
    

    we cannot combine both filter steps.

提交回复
热议问题