all

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

发布于 2022-05-26 22:53:27

想要改进这篇文章? 提供这个问题的详细答案,包括引文和解释为什么你的答案是正确的。没有足够细节的答案可能会被编辑或删除。

我在添加数组的所有元素以及平均它们时遇到问题。我将如何做到这一点并使用我目前拥有的代码来实现它?这些元素应该按照我在下面的定义。

<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>
关注者
0
被浏览
19
1 个回答
  • 面试哥
    面试哥 2022-05-26
    为面试而生,有面试问题,就找面试哥。
    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 );
    

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看