so the reason parseInt
gives you 1 is because parseInt
traverses the string up to the first non number character, and returns the result. It gets tripped up by '+' and just returns 1
. Not needed for the answer but an interesting bit to add nonetheless. If you used the Number()
constructor instead you would always get NaN
. It's for this reason that many people will tell you to use the Number
constructor instead but I think there is a case to be made for both.
To accomplish what you want without using eval
(which you should probably just never use, see here for info on that) you'll could split the string and parse each item individually. Easiest way to accomplish this is with String.split()
and Array.map()
function isNumber(n){
return !isNaN(n)
}
var t = '1 + 5 + 7'
//split the string at whitespace into an array
//this looks like ['1', '+', '5', '+', '7']
var x = t.split(' ')
//convert each item to a number, parseInt works here as well
//this ouputs [1, NaN, 5, NaN, 7]
.map(Number)
//filter out anything that couldn't be converted
//and you're left with [1,5,7]
.filter(isNumber)
//add each item in the array to get a sum result
.reduce((a, b) => a + b)
console.log(x) //outputs 13
This only works if the operator in the string is the same, but you could add a test to see which operator is which, and pass different functions to reduce to get a desired result. If you are interesting mastering javascript I highly encourage reading more about Array.map(), Array.filter(), and Array.reduce(). These functions are extremely useful, and probably my favorite set of functions in the entire language.