How to convert comma separated string into numeric array in javascript

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

    This is an easy and quick solution when the string value is proper with the comma(,).

    But if the string is with the last character with the comma, Which makes a blank array element, and this is also removed extra spaces around it.

    "123,234,345,"

    So I suggest using push()

    var arr = [], str="123,234,345,"
    str.split(",").map(function(item){
        if(item.trim()!=''){arr.push(item.trim())}
    })
    

提交回复
热议问题