[英]How can I add up two or more array elements (numbers)
I want to add up all of the element from var string to each other. 我想将var字符串中的所有元素加在一起。 I did try this but now I want to do this for each element.
我确实尝试过,但是现在我想针对每个元素执行此操作。
var operator = document.getElementById("operation").value;
var number = document.getElementById("numbers").value;
var string = number.split(",");
var number1 = string[0];
var number2 = string[1];
var sum = number1 + number2;
document.getElementById("result").innerHTML = parseInt(sum);
Any help is welcome! 欢迎任何帮助!
Use reduce()
and don't forget to cast your string
into int
: 使用
reduce()
,不要忘记将string
转换为int
:
var number = "1,2,3,4,5"
var sum = number.split(",").reduce(function (total, num) {
return total + parseInt(num);
}, 0);
You can do R. Saban's way and there are also other ways as well. 您可以使用R. Saban的方法,还有其他方法。 For example try this:
例如,尝试以下操作:
var start = 0; // Using this to add each element in the array starting from 0, look below
var number = document.getElementById("numbers").value;
var string = number.split(",");
string.forEach(function (num) {
start += parseInt(num);
});
// variable "start" will hold the end result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.