function Accumulator(){
this.length = 0;
this.average = 0;
this.sum = 0;
this.max = Number.NEGATIVE_INFINITY; //无穷小
this.min = Number.POSITIVE_INFINITY; //无穷大
this.add = function(val){
this.length++;
this.average = this.average + ( val - this.average ) / this.length;
this.sum += val;
if(val > this.max){
this.max = val;
}
if(val < this.min){
this.min = val;
}
}
}
每添加一个数字都会自动算出总数、平均值、最大、最小值、长度。
var accumulator = new Accumulator();
accumulator.add(16);
accumulator.add(32);
accumulator.add(64);
accumulator.sum; // 112
accumulator.average; // 37.333333333333336
accumulator.max; // 64
accumulator.min; // 16
accumulator.length; // 3