# 如何计算数组中元素的总和和平均值？

2020/10/21 02:42 · javascript ·  · 0评论

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

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

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

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

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

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

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

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

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

http://www.airpair.com/javascript/javascript-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])
``````

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

A =（1 / n）Σxi （i = 1至n） ...所以：x1 / n + x2 / n + ... + xn / n

reduce方法的签名是

``````reduce(callback[,default_previous_value])
``````

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

• p：先前计算的结果
• c：当前值（来自当前索引）
• i：当前数组元素的索引值
• a：电流减少的数组

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

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

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

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

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

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

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

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

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

``````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/>");
``````

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

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

``````Math.sum = (...a) => Array.prototype.reduce.call(a,(a,b) => a+b)

Math.avg = (...a) => this.sum(...a)/a.length;
``````

``````var maxOne = Math.max(1,2,3,4) // 4;
``````

``````var sumNum = Math.sum(1,2,3,4) // 10
``````

``````var sumNum = Math.sum.apply(null,[1,2,3,4]) // 10
``````

``````var maxOne = Math.max.apply(null,[1,2,3,4]) // 4
``````

``````Math.average = function(input) {
this.output = 0;
for (this.i = 0; this.i < input.length; this.i++) {
this.output+=Number(input[this.i]);
}
return this.output/input.length;
}
``````

``````Math.sum = function(input) {
this.output = 0;
for (this.i = 0; this.i < input.length; this.i++) {
this.output+=Number(input[this.i]);
}
return this.output;
}
``````

``````alert(Math.sum([5,5,5])); //alerts “15”
``````

``````let avg = [1,2,3].reduce((a,v,i)=>(a*i+v)/(i+1));
``````

``````let sum = [1,2,3].reduce((a,b)=>a+b);
``````

``````var numbers = [], count = sum = avg = 0;
``````

``````while ( count < 12 )
numbers.push( count++ );
``````

``````numbers.forEach(function(n){
sum += n;
avg = sum / numbers.length;
});
``````

``````// Sum: 66, Avg: 5.5
console.log( 'Sum: ' + sum + ', Avg: ' + avg );
``````

2.）`array.length`在javascript中完全可靠，我更喜欢，`Array.reduce`因为`a=[1,3];a[1000]=5;`现在`a.length`会返回`1001`

``````function getAverage(arry){
// check if array
if(!(Object.prototype.toString.call(arry) === '[object Array]')){
return 0;
}
var sum = 0, count = 0;
sum = arry.reduce(function(previousValue, currentValue, index, array) {
if(isFinite(currentValue)){
count++;
return previousValue+ parseFloat(currentValue);
}
return previousValue;
}, sum);
return count ? sum / count : 0;
};
``````
``````Array.prototype.avg=function(fn){
fn =fn || function(e,i){return e};
return (this.map(fn).reduce(function(a,b){return parseFloat(a)+parseFloat(b)},0) / this.length ) ;
};
``````

``````[ 1 , 2 , 3].avg() ;  //-> OUT : 2

[{age:25},{age:26},{age:27}].avg(function(e){return e.age}); // OUT : 26
``````

`avg = [1,2,3].reduce((a,b) => (a+b);`

``````s=Date.now();for(i=0;i<100000;i++){ n=[1,2,3]; a=n.reduce((a,b) => (a+b)) / n.length };
console.log("100k reduce took " + (Date.now()-s) + "ms.");

s=Date.now();for(i=0;i<100000;i++){n=[1,2,3]; nl=n.length; a=0; for(j=nl-1;j>0;j--){a=a+n[j];} a/nl };
console.log("100k for loop took " + (Date.now()-s) + "ms.");

s=Date.now();for(i=0;i<1000000;i++){n=[1,2,3]; nl=n.length; a=0; for(j=nl-1;j>0;j--){a=a+n[j];} a/nl };
console.log("1M for loop took " + (Date.now()-s) + "ms.");

s=Date.now();for(i=0;i<1000000;i++){ n=[1,2,3]; a=n.reduce((a,b) => (a+b)) / n.length };
console.log("1M reduce took " + (Date.now()-s) + "ms.");

/*
* RESULT on Chrome 51
* 100k reduce took 26ms.
* 100k for loop took 35ms.
* 10M for loop took 126ms.
* 10M reduce took 209ms.
*/``````

``````var elmt = [0, 1, 2,3, 4, 7, 8, 9, 10, 11], l = elmt.length, i = -1, sum = 0;
for (; ++i < l; sum += elmt[i])
;
document.body.appendChild(document.createTextNode('The sum of all the elements is: ' + sum + ' The average of all the elements is: ' + (sum / l)));
``````

``````var k=elmt.reduce(function(a,b){return parseFloat(a+parseFloat(b));})
var avg=k/elmt.length;
console.log(avg);
``````

2）当（a）9 + parseFloat（“ 1”）的加法发生时，尽管结果将是“ 10”，但它将是我们不想要的字符串，所以我再次使用parseFloat。

``````function numAvg(num){
var total = 0;
for(var i = 0;i < num.length; i++) {
total+=num[i];
}
}
``````

``````var average = arr.reduce((sum,item,index,arr)=>index !== arr.length-1?sum+item:sum+item/arr.length,0)
``````

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

function average(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++) {
total += arr[i];
}
console.log(Math.round(total/arr.length));
}

average(elmts);
``````

``````const numbers = [1,2,3,4];
const count = numbers.length;
const average = numbers.map(x => x/count).reduce(reducer);
console.log(average); // 2.5
``````

``````const numbers = [1,2,3,4];
console.log(average); // 2.5
``````

``````const r = function (adder, value) {
};
const m = function (x) {
return x/count;
};
const average = numbers.map(m).reduce(r);
console.log(average); // 2.5
``````

``````const average1 = numbers
.map(function (x) {
return x/count;
})
});
console.log(average1);
``````

``````// Assumes an array with only values that can be parsed to a Float
var reducer = function(cumulativeAverage, currentValue, currentIndex) {
// 1. multiply average by currentIndex to find cumulative sum of previous elements
// 2. add currentValue to get cumulative sum, including current element
// 3. divide by total number of elements, including current element (zero-based index + 1)
return (cumulativeAverage * currentIndex + parseFloat(currentValue))/(currentIndex + 1)
}
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(reducer, 0)); // => 5.5
console.log([].reduce(reducer, 0)); // => 0
console.log([0].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0
console.log([,,,].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0
``````

``````/**
* Computes the recursive average of an indefinite set
* @param {Iterable<number>} set iterable sequence to average
* @param {number} initAvg initial average value
* @param {number} initCount initial average count
*/
function average(set, initAvg, initCount) {
if (!set || !set[Symbol.iterator])
throw Error("must pass an iterable sequence");

let avg = initAvg || 0;
let avgCnt = initCount || 0;
for (let x of set) {
avgCnt += 1;
avg = avg * ((avgCnt - 1) / avgCnt) + x / avgCnt;
}
return avg; // or {avg: avg, count: avgCnt};
}

average([2, 4, 6]);    //returns 4
average([4, 6], 2, 1); //returns 4
average([6], 3, 2);    //returns 4
average({
*[Symbol.iterator]() {
yield 2; yield 4; yield 6;
}
});                    //returns 4
``````

• 您不对所有元素求和，这可能导致大量元素无法存储在64位浮点数中。
• 如果可以使用其他值，则可以“更新”现有平均值。
• 您可以在不知道序列长度的情况下进行滚动平均。

• 招致更多分裂
• 不是无限的-仅限Number.MAX_SAFE_INTEGER个项目，除非您雇用 `BigNumber`

## HTML内容平均灰度

``````<p>Elements for an average: <span class="m">2</span>, <span class="m">4</span>,
<span class="m">2</span>, <span class="m">3</span>.
</p>
``````

``````var A = \$('.m')
.map(function(idx) { return  parseInt(\$(this).html()) })
.get();
var AVG = A.reduce(function(a,b){return a+b}) / A5.length;
``````

var arr = [1,2,3,4,5]

``````function avg(arr){
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += parseFloat(arr[i])
}
return sum / i;
}
``````

avg（arr）====== >>>> 3

``````    var scores =[90, 98, 89, 100, 100, 86, 94];
var sum = 0;
var avg = 0;
for(var i = 0; i < scores.length;i++){
//Taking sum of all the arraylist
sum = sum + scores[i];
}
//Taking average
avg = sum/scores.length;
//this is the function to round a decimal no
var round = avg.toFixed();
console.log(round);
``````

``````let d3 = require('d3');
let array = [1,2,3,4];
let sum = d3.sum(array); //10
let mean = d3.mean(array); //2.5
let median = d3.median(array);
``````