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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10359907/
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-24 01:01:47  来源:igfitidea点击:

How to compute the sum and average of elements in an array?

javascriptarraysaverage

提问by jonathan miller

I am having problems adding all the elements of an array as well as averaging them out. How would I do this and implement it with the code I currently have? The elements are supposed to be defined as I have it below.

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

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

采纳答案by Marcus Recck

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

Just iterate through the array, since your values are strings, they have to be converted to an integer first. And average is just the sum of values divided by the number of values.

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

回答by Sergi Mansilla

A solution I consider more elegant:

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

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

回答by Abdennour TOUMI

ES6

ES6

const average = arr => arr.reduce( ( p, c ) => p + c, 0 ) / arr.length;
    
const result = average( [ 4, 4, 5, 6, 6 ] ); // 5
    
console.log(result);

回答by Tomasz Mularczyk

Calculating average (mean) using reduceand ES6:

使用reduce和ES6计算平均值(mean):

const average = list => list.reduce((prev, curr) => prev + curr) / list.length;

const list = [0, 10, 20, 30]
average(list) // 15

回答by Shimon Doodkin

generally average using one-liner reduce is like this

一般平均使用单行减少是这样的

elements.reduce(function(sum, a,i,ar) { sum += a;  return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0);

specifically to question asked

特别是问的问题

elements.reduce(function(sum, a,i,ar) { sum += parseFloat(a);  return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0);

an efficient version is like

一个有效的版本就像

elements.reduce(function(sum, a) { return sum + a },0)/(elements.length||1);

Understand Javascript Array Reduce in 1 Minute http://www.airpair.com/javascript/javascript-array-reduce

一分钟了解 Javascript Array Reduce http://www.airpair.com/javascript/javascript-array-reduce

as gotofritz pointed out seems Array.reduce skips undefined values. so here is a fix:

正如gotofritz 指出的,似乎 Array.reduce 会跳过未定义的值。所以这是一个修复:

(function average(arr){var finalstate=arr.reduce(function(state,a) { state.sum+=a;state.count+=1; return state },{sum:0,count:0}); return finalstate.sum/finalstate.count})([2,,,6])

回答by Ludovic Frérot

Let's imagine we have an array of integers like this:

假设我们有一个这样的整数数组:

var values = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

The average is obtained with the following formula

平均值由以下公式获得

A= (1/n)Σxi( with i = 1 to n )... So: x1/n + x2/n + ... + xn/n

A= (1/n)Σxi ( i = 1 to n )... 所以:x1/n + x2/n + ... + xn/n

We divide the current value by the number of values and add the previous result to the returned value.

我们将当前值除以值的数量,并将先前的结果添加到返回值中。

The reduce method signature is

减少方法签名是

reduce(callback[,default_previous_value])

The reduce callback function takes the following parameters:

reduce 回调函数采用以下参数:

  • p: Result of the previous calculation
  • c: Current value (from the current index)
  • i: Current array element's index value
  • a: The current reduced Array
  • p: 上次计算的结果
  • c: 当前值(来自当前索引)
  • i: 当前数组元素的索引值
  • a: 当前减少的 Array

The second reduce's parameter is the default value... (Used in case the array is empty).

第二个reduce 的参数是默认值...(在数组为空的情况下使用)。

So the average reduce method will be:

所以平均减少方法将是:

var avg = values.reduce(function(p,c,i,a){return p + (c/a.length)},0);

If you prefer you can create a separate function

如果您愿意,您可以创建一个单独的功能

function average(p,c,i,a){return p + (c/a.length)};
function sum(p,c){return p + c)};

And then simply refer to the callback method signature

然后简单的参考回调方法签名

var avg = values.reduce(average,0);
var sum= values.reduce(sum,0);

Or Augment the Array prototype directly..

或者直接扩充数组原型..

Array.prototype.sum = Array.prototype.sum || function (){
  return this.reduce(function(p,c){return p+c},0);
};

It's possible to divide the value each time the reduce method is called..

每次调用reduce方法时都可以对值进行除法..

Array.prototype.avg = Array.prototype.avg || function () {
  return this.reduce(function(p,c,i,a){return p+(c/a.length)},0);
};

Or even better, using the previously definedArray.protoype.sum()

或者甚至更好,使用之前定义的Array.protoype.sum()

method, optimize the process my calling the division only once :)

方法,优化我只调用一次除法的过程:)

Array.prototype.avg = Array.prototype.avg || function () {
  return this.sum()/this.length; 
};

Then on any Array object of the scope:

然后在作用域的任何 Array 对象上:

[2, 6].avg();// -> 4
[2, 6].sum();// -> 8

NB: an empty array with return a NaN wish is more correct than 0 in my point of view and can be useful in specific use cases.

注意:在我看来,返回 NaN 愿望的空数组比 0 更正确,并且在特定用例中很有用。

回答by Geng Jiawen

You can also use lodash, _.sum(array) and _.mean(array) in Math part (also have other convenient stuff).

您还可以在数学部分使用lodash、 _.sum(array) 和 _.mean(array) (还有其他方便的东西)。

_.sum([4, 2, 8, 6]);
// => 20
_.mean([4, 2, 8, 6]);
// => 5

回答by Johann Echavarria

Not the fastest, but the shortest and in one line is using map() & reduce():

不是最快的,但最短的一行是使用 map() 和 reduce():

var average = [7,14,21].map(function(x,i,arr){return x/arr.length}).reduce(function(a,b){return a + b})

回答by Keith

I use these methods in my personal library:

我在我的个人库中使用这些方法:

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

Array.prototype.average = Array.prototype.average || function() {
  return this.sum() / (this.length || 1);
}

EDIT: To use them, simply ask the array for its sum or average, like:

编辑:要使用它们,只需询问数组的总和或平均值,例如:

[1,2,3].sum() // = 6
[1,2,3].average() // = 2

回答by Phil Cooper

One sneaky way you could do it although it does require the use of (the much hated) eval().

一种偷偷摸摸的方法可以做到,尽管它确实需要使用(非常讨厌的)eval()。

var sum = eval(elmt.join('+')), avg = sum / elmt.length;
document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>");

Just thought I'd post this as one of those 'outside the box' options. You never know, the slyness might grant you (or taketh away) a point.

只是想我会将此作为“框外”选项之一发布。你永远不知道,狡猾可能会给你(或带走)一分。