Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript split string of ints to array

Tags:

javascript

I have a string MyString like this:

var MyString = "32,43,545,34,23,";

I'd like to have this in an array of ints.

If I do this:

var MyArray = MyString.split(",");

I get an array of strings. How do I get an array of ints?

I know I can loop over the array and do a parseInt on each element but I was wondering if there's a better way to do it.

Thanks.

like image 618
frenchie Avatar asked Aug 21 '26 13:08

frenchie


2 Answers

unfortunatelly you'll have to manually walk through the array and change each element like this:

var MyArray = MyString.split(",");
for (var i=0, LoopTimes = MyArray.length; i < LoopTimes; i++){
    MyArray[i] = parseInt(MyArray[i], 10);
}

or you can also have a look at this: http://phpjs.org/functions/array_walk:349

like image 83
Gavriel Avatar answered Aug 23 '26 03:08

Gavriel


'32,43,545,34,23'.split(',').map(Number)
like image 45
katspaugh Avatar answered Aug 23 '26 03:08

katspaugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!