简体   繁体   中英

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. 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 :

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM