javascript 数组中数字的总和 [英] Sum of numbers in an array with javascript
本文介绍了javascript 数组中数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取数组中所有数字的总和.我试图以最简单的方式做到这一点,但总和显示 NAN.为什么会这样?请帮忙
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>
推荐答案
您正在为每次循环迭代创建一个新的 sum
变量,并且您也在声明之前使用它,因此 undefined +<some numer>
给你 NaN
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>
此外,使用 for 循环也不错:
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);
这篇关于javascript 数组中数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文