gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:18:31 28 4
gpt4 key购买 nike

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

<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>

最佳答案

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

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}.`);

关于javascript - 如何计算数组中元素的总和和平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10359907/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com