Finding the sum of an array in javascript

时间:2015-11-12 11:36:21

标签: javascript

I have to write 6 small JavaScript scripts for school and I've got them all working apart from this one.

function calculate() {
    var numbers = [
        document.getElementById("num_one").value ,
        document.getElementById("num_two").value ,
        document.getElementById("num_three").value 
    ];
    var sum = numbers[0] + numbers[1] + numbers[2];
    document.getElementById("display_sum").innerHTML = sum;
}

The user is supposed to enter 3 numbers click a button and it should add them all togther or "find the sum".

My Problem is, it just joins the numbers togther instead of adding them. Does anyone know a way to fix this?

11 个答案:

答案 0 :(得分:16)

You are "summing" string variables so Javascript is concatenating them.

You need to convert them to numbers in order to have an arithmetic sum:

function calculate() {
        var numbers = [
            document.getElementById("num_one").value ,
            document.getElementById("num_two").value ,
            document.getElementById("num_three").value 
        ];
        var sum = Number(numbers[0]) + Number(numbers[1]) + Number(numbers[2]);
        document.getElementById("display_sum").innerHTML = sum;
        }

答案 1 :(得分:7)

Parse string using parseFloat(), parseInt() or Number(), for converting it's to number. Otherwise + will just do string concatenation , since the values are string.

function calculate() {
  var numbers = [
    document.getElementById("num_one").value,
    document.getElementById("num_two").value,
    document.getElementById("num_three").value
  ];
  var sum = parseFloat(numbers[0]) + parseFloat(numbers[1],) + parseFloat(numbers[2]);
  document.getElementById("display_sum").innerHTML = sum;
}

function calculate() {
  var numbers = [
    document.getElementById("num_one").value,
    document.getElementById("num_two").value,
    document.getElementById("num_three").value
  ];
  var sum = Number(numbers[0]) + Number(numbers[1]) + Number(numbers[2]);
  document.getElementById("display_sum").innerHTML = sum;
}

function calculate() {
  var numbers = [
    document.getElementById("num_one").value,
    document.getElementById("num_two").value,
    document.getElementById("num_three").value
  ];
  var sum = parseInt(numbers[0], 10) + parseInt(numbers[1], 10) + parseInt(numbers[2], 10);
  document.getElementById("display_sum").innerHTML = sum;
}

答案 2 :(得分:4)

The value property is string. In order to use it in arithmetic operations, you need to parse it to integers. The simpliest way to do this in JS is +x. You can use Array.prototype.map and Array.prototype.reduce to make it easier:

var ids = ['num_one', 'num_two', 'num_three'];
var sum = ids
    .map(function(x) { return +document.getElementById(x).value; })
    .reduce(function(a,b) { return a+b; }, 0);

With this way, you will be able to introduce new elements into calculations with minimal changes.

答案 3 :(得分:2)

.value return String you need convert it to Number,

you can do it with parseInt or parseFloat(if you have float values), or with Number() or just add + before value

var numbers = [
    +document.getElementById("num_one").value,
    +document.getElementById("num_two").value,
    +document.getElementById("num_three").value
];

or

var numbers = [
   Number(document.getElementById("num_one").value),
   Number(document.getElementById("num_two").value),
   Number(document.getElementById("num_three").value)
];

or

var numbers = [
   parseInt(document.getElementById("num_one").value, 10),
   parseInt(document.getElementById("num_two").value, 10),
   parseInt(document.getElementById("num_three").value, 10)
];

答案 4 :(得分:2)

The shortest approach is to use Array.prototype.map

The map() method creates a new array with the results of calling a provided function on every element in this array.

in combination with Number

The Number JavaScript object is a wrapper object allowing you to work with numerical values. A Number object is created using the Number() constructor.

The primary uses for the Number object are:

  • If the argument cannot be converted into a number, it returns NaN.
  • In a non-constructor context (i.e., without the new operator), Number can be used to perform a type conversion.

and then Array.prototype.reduce

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

in combination with a callback like

function (a, b) {
    return a + b;
}

Together in a single line with your code wrapped:

function calculate() {
    var numbers = [
            document.getElementById("num_one").value,
            document.getElementById("num_two").value,
            document.getElementById("num_three").value
        ],
        sum = numbers.map(Number).reduce(function (a, b) { return a + b; });
    document.getElementById("display_sum").innerHTML = sum;
}

答案 5 :(得分:2)

es6的一行中的可扩展解决方案:

var sum = numbers.reduce((a, b) => Number(a) + Number(b), 0);

确保在那里包含initialValue - 它将保证执行回调,并且在数组不包含值/一个值的情况下返回一个数字。

More info on reduce

答案 6 :(得分:1)

Depending on whether your input numbers are integers or decimals, you can use parseInt or parseFloat.

答案 7 :(得分:1)

There are already plenty of reasonable answers, but here's a neat shorthand alternative:

var sum = +numbers[0] + +numbers[1] + +numbers[2];

答案 8 :(得分:1)

By default, javascript treats input values as strings. So you have to manually convert them to integers like this:

var numbers = [
    document.getElementById("num_one").value ,
    document.getElementById("num_two").value ,
    document.getElementById("num_three").value 
];

document.getElementById("display_sum").innerHTML =
    numbers
        .reduce(function(sum, element) { return sum + parseInt(element, 10);}, 0);

What is good about this code, is that if you need to calculate for more than three elements you only need to modify your numbers array.

答案 9 :(得分:1)

I think you can use an array to store the inputs like

<script>
var numbers;

function push(){
  numbers.push(getDocumentById("someid").val;
}


function calculate(){
  var sum=0;
  for(i=0; i<numbers.len; i++){
    sum=sum + numbers[i];
  }
    alert(sum);
}

</script>

<div>
  <button id="someid" value=20 onClick="addToArray();">click to push</button>
</div>

<div>
  <button id="calc" onClick="calculate();">click to calculate</button>
</div>

答案 10 :(得分:1)

以下将解决问题:

function calculate() {
var numbers = [
    +(document.getElementById("num_one").value) ,
    +(document.getElementById("num_two").value) ,
    +(document.getElementById("num_three").value) 
];
var sum = numbers[0] + numbers[1] + numbers[2];
document.getElementById("display_sum").innerHTML = sum;
}