views:

58

answers:

3

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.

+2  A: 

You can just loop through it:

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

    stringBits[i] = parseInt(stringBits[i]);
}
I.devries
I wanted to avoid doing that where possible, it seems like an unnecessary loop when really all it will do is make my code a little cleaner.
Toby
In JS, looping is the only way to do something with every entry of an array.
I.devries
If all you want to do is make your code a little cleaner, you could provide a method (e.g. extractIntsFromString) that converts your string to an array of integers. Then use the elements of the integer array for your calculations. Once the type conversion out of the way, you can focus on the cleaner code that, now, just performs the mathematical functions.
dpb
A: 

If you add a plus (+) sign in front of your strings they should be converted to numeric.

For example, this will print 3:

var x = "1";
var y = "2";
alert((+x) + (+y));

But I am not sure if this is portable to all browsers.

Your code will become:

var stringBits = theString.split('/');
var result = (+stringBits[0]) + (+stringBits[3]) / (+stringBits[1]);

But this is just a hack, so use with care.

I think the parseInt states better what you are trying to do, but you should delegate this responsibility to another method that returns the final data that you need to process. Convert and then process, don’t convert while processing. Your code will be easier to read.

dpb
A: 

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) })
stereofrog