Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing every element of an array as an integer

I have a string which I need to split into an array and then perform mathematical functions on each element of the array.

Currently I am doing something like this. (Actually, I am doing nothing like this, but this is a very simple example to explain my question!

var stringBits = theString.split('/');

var result = parseInt(stringBits[0]) + parseInt(stringBits[3]) / parseInt(stringBits[1]);

What I would like to know is if there is a way I can convert every element of an array into a certain type that would stop me from having to explicitly parse it each time.

like image 655
Toby Avatar asked Nov 20 '09 10:11

Toby


3 Answers

An easier method is to map to the Number object

result= stringBits.map(Number); 
like image 72
Mihai Avatar answered Oct 14 '22 09:10

Mihai


javascript 1.6. has map() ( https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map ), so you can do something like

intArray = someArray.map(function(e) { return parseInt(e) })
like image 21
user187291 Avatar answered Oct 14 '22 08:10

user187291


You can just loop through it:

for(var i = 0; i < stringBits.length; i++) {

    stringBits[i] = parseInt(stringBits[i]);
}
like image 28
I.devries Avatar answered Oct 14 '22 08:10

I.devries