Sum of numbers in an array with javascript

非 Y 不嫁゛ 提交于 2021-01-27 17:31:32

问题


I am trying to get the sum of all the numbers in an array. I am trying to do it in the most simple way but the sum display NAN. why is this so? please help

var numbers = [45, 34, 12, 10, 8, 9];
var i;

for(i=0 ; i<numbers.length; i++){
  var sum = sum + numbers[i];
  //alert(sum);
}
document.getElementById("demo").innerHTML="The sum is" + sum;
<h2>JavaScript</h2>
<p>This example finds the sum of all numbers in an array:</p>
<p id="demo"></p>

回答1:


var sum = [1, 2, 3].reduce(add, 0);
function add(a, b) {
  return a + b;
}
console.log(sum); // 6



回答2:


You are creating a new sum variable for each loop iteration, also you are using it before it's declared hence undefined + <some numer> giving you NaN

var total = 0;
[45, 34, 12, 10, 8, 9].forEach(num => {total += num});

document.getElementById("demo").innerHTML=`The sum is: ${total}`;
<h2>JavaScript</h2>
<p>This example finds the sum of all numbers in an array:</p>
<p id="demo"></p>

Also, nice hack with for loop:

var total = 0;
var numbers = [45, 34, 12, 10, 8, 9];
for (var i = 0; i < numbers.length; total += numbers[i++]);

console.log('total', total);



回答3:


The problem is that sum is defined outside the scope of your function, so what you're actually doing is var sum = undefined + numbers[i] (which is NaN).

Even then, it is better to use either reduce or arrow functions (if you can use ES6).

Using reduce():

var numbers = [45, 34, 12, 10, 8, 9],
    sum     = numbers.reduce(function(a, b) { return a + b; }, 0);
    
document.getElementById('output').innerHTML = sum;
<div id="output"></div>

Using arrow functions:

var numbers = [45, 34, 12, 10, 8, 9],
    sum     = numbers.reduce((a, b) => a + b, 0);
    
document.getElementById('output').innerHTML = sum;
<div id="output"></div>



回答4:


The problem is that you're declaring the sum variable inside the loop and you don't initialize it.

So you get undefined + numbers[i] which equals NaN.

var numbers = [45, 34, 12, 10, 8, 9];
var i;
var sum = 0;

for(i=0 ; i<numbers.length; i++){
sum = sum + numbers[i];
}

document.getElementById("demo").innerHTML="The sum is" + sum;
<p id="demo"></p>



回答5:


You're instantiating sum each time, take var sum out the loop and jut have sum.

Also you could use Array.prototype.reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce



来源:https://stackoverflow.com/questions/52686772/sum-of-numbers-in-an-array-with-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!