How to convert comma separated string into numeric

2020-05-30 00:55发布

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 = "130,235,342,124 ";

9条回答
太酷不给撩
2楼-- · 2020-05-30 01:46

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())}
})
查看更多
够拽才男人
3楼-- · 2020-05-30 01:47

The split() method is used to split a string into an array of substrings, and returns the new array.

Syntax:
  string.split(separator,limit)


arr =  strVale.split(',');

SEE HERE

查看更多
贪生不怕死
4楼-- · 2020-05-30 01:50

just you need to use couple of methods for this, that's it!

var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});

the output will be the array of numbers.

查看更多
登录 后发表回答