使用JS查找数组的平均值 [英] Finding the average of an array using JS

查看:31
本文介绍了使用JS查找数组的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找但没有找到关于堆栈溢出的简单问答,以寻找数组的平均值.

I've been looking and haven't found a simple question and answer on stack overflow looking into finding the average of an array.

这是我拥有的数组

const grades = [80, 77, 88, 95, 68];

我一开始以为这个问题的答案是这样的:

I first thought that the answer to this problem would be something like this:

let avg = (grades / grades.length) * grades.length
console.log(avg)

然而,这给了我 NaN 的输出.

However, this gave me an output of NaN.

然后我尝试了这个:

for (let grade of grades)
    avg = (grade / grades.length) * grades.length
console.log(avg)

这给了我 68 的输出.(我不知道为什么).

This gave me an output of 68. (I'm not sure why).

因此,我有两个问题.1.为什么我的输出是68?和 2. 有人能帮我真正找到数组的平均值吗?

So with this I have two questions. 1. Why was my output 68? and 2. Could somebody help me out with actually finding the average of an array?

推荐答案

您可以通过将所有元素相加然后除以元素数量来计算平均值.

You calculate an average by adding all the elements and then dividing by the number of elements.

var total = 0;
for(var i = 0; i < grades.length; i++) {
    total += grades[i];
}
var avg = total / grades.length;

结果为 68 的原因是因为在循环中,您不断覆盖平均值,因此最终值将是您上次计算的结果.而你的除法和乘法的成绩.length 相互抵消.

The reason you got 68 as your result is because in your loop, you keep overwriting your average, so the final value will be the result of your last calculation. And your division and multiplication by grades.length cancel each other out.

这篇关于使用JS查找数组的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆