javascript javascript中一串一位数字的总和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10052254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum of a string of one-digit numbers in javascript?
提问by SorryEh
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.
我需要做某种求和函数,将 1+2+3+4+5 相加并检查它是否等于 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++)
我想我需要使用 for 循环来遍历数字,例如 for (var i = 0, length = left.length; i < length; i++)
But I'm not sure how to add each number from there.
但我不确定如何从那里添加每个数字。
EDITthe var is actually being pulled in from a field. so var left = document.blah.blah
编辑var 实际上是从一个字段中拉进来的。所以 var left = document.blah.blah
回答by Joseph
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));?
回答by Pete
- Find the length of the string
- then in a temp Variable store the value pow(10,length-1)
- if you apply module function (left%temp) you will ge the Last significant digit
- you can use this digit to add
- repeat the process till the length of the string left is 0 6 Repeat all the steps above for the right as well and then compare the values
- 查找字符串的长度
- 然后在临时变量中存储值 pow(10,length-1)
- 如果您应用模块功能 (left%temp),您将获得最后一位有效数字
- 你可以用这个数字来添加
- 重复这个过程,直到左边的字符串长度为 0 6 对右边也重复上述所有步骤,然后比较值
Note: convert the string to int using parseInt function
注意:使用 parseInt 函数将字符串转换为 int
回答by ninjagecko
var sum = function(a,b){return a+b}
function stringSum(s) {
var int = function(x){return parseInt(x,10)}
return s.split('').map(int).reduce(sum);
}
stringSum(a) == stringSum(b)