小编典典

如何计算数组中元素的总和和平均值?

javascript

我在添加数组的所有元素以及将它们取平均值时遇到了问题。我该怎么做,并用我现在拥有的代码实现它?这些元素应该定义如下。

<script type="text/javascript">
//<![CDATA[

var i;
var elmt = new Array();

elmt[0] = "0";
elmt[1] = "1";
elmt[2] = "2";
elmt[3] = "3";
elmt[4] = "4";
elmt[5] = "7";
elmt[6] = "8";
elmt[7] = "9";
elmt[8] = "10";
elmt[9] = "11";

// Problem here
for (i = 9; i < 10; i++){
  document.write("The sum of all the elements is: " + /* Problem here */ + " The average of all the elements is: " + /* Problem here */ + "<br/>");
}

//]]>
</script>

阅读 630

收藏
2020-05-01

共2个答案

小编典典

var sum = 0;
for( var i = 0; i < elmt.length; i++ ){
sum += parseInt( elmt[i], 10 ); //don’t forget to add the base
}

var avg = sum/elmt.length;

document.write( "The sum of all the elements is: " + sum + " The average is: " + avg );

只需遍历数组,因为您的值是字符串,因此必须先将它们转换为整数。平均值就是值的总和除以值的数量。

2020-05-01
小编典典

我认为更优雅的解决方案:

const sum = times.reduce((a, b) => a + b, 0);
const avg = (sum / times.length) || 0;

console.log(`The sum is: ${sum}. The average is: ${avg}.`);
2020-05-07