JavaScript's eval
function was mentioned in a comment by Oliver Morgan and I just wanted to flush out how you could use eval
as a solution to your problem.
The eval
function takes a string and then returns the value of that string considered as a math operation. For example,
eval("3 + 4")
will return 7 as 3 + 4 = 7.
This helps in your case because you have an array of strings that you want you want to treat as the mathematical operators and operands that they represent.
myArray = ["225", "+", "15", "-", "10"];
Without converting any of the strings in your array into integers or operators you could write
eval(myArray[0] + myArray[1] + myArray[2]);
which will translate to
eval("225" + "+" + "15");
which will translate to
eval("225 + 15");
which will return 240, the value of adding 225 to 15.
Or even more generic:
eval(myArray.join(' '));
which will translate to
eval("225 + 15 - 10");
which will return 230, the value of adding 15 to 225 and substract 10. So you can see that in your case it may be possible to skip converting the strings in your array into integers and operators and, as Oliver Morgan said, just eval
it.