简体   繁体   English

如何添加两个或多个数组元素(数字)

[英]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.

相关问题 给定一个带数字的数组,如何编写一个递归函数,当2个元素加到目标时,它会在数组中找到索引? - Given an array with numbers, how can I write a recursive function that finds indices in the array when 2 elements add up to a target? 仅当元素在页面上超过两个时,才能如何向元素添加另一个类? - How can i add another class to elements only if they are more than two on page? 如何生成数组元素的随机组合,使它们的值之和介于两个数字之间? - How can I generate a random combination of array elements so that the sum of their values is between two numbers? 如何添加两个 CountUp 元素 - How can I add two CountUp elements 查找数组中的一个或多个数字是否可以等于某个数字 - Finding if one ore more numbers in an array can add up to be equal to a certain number 如何添加出现在班级名称中的数字? - How can I add up numbers that appear in class names? 如何在 ReactJS 的对象中添加更多元素? - How can i add more elements in my object in ReactJS? Javascript-如何将一个数组中的点添加到另一个数组中-所以我可以将它们相加并比较两个数组 - Javascript - how to add points from one array to another - so I can tally them up and compare the two 如何将具有两个单独对象的数组列表生成的表列中的所有值相加? - How can I add up all the values in a table column generated from an Array list with two separate objects? 将数组中的数字相加 - add up numbers in array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM