Sum of a string of one-digit numbers in javascript?
javascript
Solution
DEMO
var left = "12345"
var right = "12345"
function add(string) {
string = string.split(''); //split into individual characters
var sum = 0; //have a storage ready
for (var i = 0; i < string.length; i++) { //iterate through
sum += parseInt(string[i],10); //convert from string to int
}
return sum; //return when done
}
alert(add(left) === add(right));
Problem
I'm trying to write a script that adds the left side of a string and validates it against the right side. For example: ``` var left = "12345" var right = "34567" ``` I need to do some sort of sum function that adds 1+2+3+4+5 and checks if it equals 3+4+5+6+7. I just don't have a clue how to do it. I think I need to use a for loop to iterate through the numbers such as for (var i = 0, length = left.length; i < length; i++) But I'm not sure how to add each number from there. EDIT the var is actually being pulled in from a field. so var left = document.blah.blah