发现使用JS的阵列的平均 [英] Finding the average of an array using JS

查看:114
本文介绍了发现使用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.

这是我在阵列

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

我首先想到的答案,这个问题将是这样的:

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

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

然而,这给了我为NaN的输出。

However this gave me an output of NaN.

于是我尝试这样做:

for ( var i = 0; i < grades.length; i ++){
    var avg = (grades[i] / 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你的结果的原因是因为在你的循环,你继续你的覆盖平均,所以最终的价值将是你最后的计算结果。和你的除法和乘法由grades.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天全站免登陆