Javascript 使用JS查找数组的平均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29544371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:33:17  来源:igfitidea点击:

Finding the average of an array using JS

javascriptarrays

提问by kdweber89

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

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

This is the array that I have

这是我拥有的数组

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)

However this gave me an output of NaN.

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

So then I tried this:

然后我尝试了这个:

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

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

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

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?

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

回答by bwroga

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;

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.

你得到 68 作为结果的原因是因为在你的循环中,你不断覆盖你的平均值,所以最终值将是你上次计算的结果。而你的除法和乘法与 grades.length 相互抵消。

回答by Andy

For the second part of your question you can use reduceto good effect here:

对于您问题的第二部分,您可以reduce在这里使用效果良好:

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

function getAvg(grades) {
  const total = grades.reduce((acc, c) => acc + c, 0);
  return total / grades.length;
}

const average = getAvg(grades);
console.log(average);

The other answers have given good insight into why you got 68, so I won't repeat it here.

其他答案已经很好地了解了为什么你得到 68,所以我不会在这里重复。

回答by Austin

With ES6 you can turn Andy's solution into as a one-liner:

使用 ES6,您可以将 Andy 的解决方案变成单行:

let average = (array) => array.reduce((a, b) => a + b) / array.length;
console.log(average([1,2,3,4,5]));

回答by pie6k

One liner challange accepted

接受一个班轮挑战

const average = arr => arr.reduce((sume, el) => sume + el, 0) / arr.length;

const average = arr => arr.reduce((sume, el) => sume + el, 0) / arr.length;

and then

进而

average([1,2,3,4]); // 2.5

average([1,2,3,4]); // 2.5

回答by Mihai

The MacGyver way,just for lulz

MacGyver 方式,只为 lulz

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

console.log(eval(a.join('+'))/a.length)

回答by baao

There's no built in function, but you can use this to get the sum,

没有内置函数,但你可以用它来求和,

Array.prototype.sum = function() {
    return this.reduce(function(a,b){return a+b;});
};

then divide by the arrays length, e.g.:

然后除以数组长度,例如:

var arr = [1,2,3,4,5]
console.log(arr.sum() / arr.length)

回答by Redu

It can simply be done with a single reduce operation as follows;

它可以简单地通过单个reduce操作完成,如下所示;

var avg = [1,2,3,4].reduce((p,c,_,a) => p + c/a.length,0);
console.log(avg)

回答by Tyler Kelley

var total = 0
grades.forEach(function (grade) {
    total += grade        
});
console.log(total / grades.length)

回答by Vlad Bezden

You can use map/reduce functions of javascript to find average. Reduce will sum them up, and map will find average.

您可以使用 javascript 的 map/reduce 函数来查找平均值。Reduce 会将它们相加,然后 map 会求平均值。

var avg = grades.map((c, i, arr) => c / arr.length).reduce((p, c) => c + p);

回答by Winters

The average function you can do is:

您可以执行的平均功能是:

const getAverage = (arr) => arr.reduce((p, c) => p + c, 0) / arr.length

Also, I suggest that use the popoular open source tool, eg. Lodash:

另外,我建议使用流行的开源工具,例如。Lodash

const _ = require('lodash')
const getAverage = (arr) => _.chain(arr)
 .sum()
 .divide(arr.length)
 .round(1)
 .value()