求平均数
@(前端)
function avgFn(){
// arguments.sort();//arguments是一个类数组集合,他不是数组,不能直接使用数组的方法
1.将类数组转换为数组
var ary = [];
for(var i = 0;i < arguments.length;i++){
ary[ary.length] = arguments[i];
}
2.给数组排序,去掉开头跟结尾,剩下的数求平均数
ary.sort(function(a,b){
retunrn a - b;
});//排序->由小到大
ary.shift();//去掉开头
ary.pop();//去掉结尾
return (eval(ary.join("+"))/ary.length).toFixed(2);
}
//ary.join("+")->把逗号换成加号转换成字符串
//eval(ary.join("+"))->将所有数字相加得到数字
//.toFixed(2);->保留俩位小数,有四舍五入
var res = avgFn(9.8,9.7,10.,9.9,9.0,9.8,3.0);
优化
//借用数组原型上的slice方法(slice() 方法可从已有的数组中返回选定的元素。),当slice执行的时候,让方法中的this变为我要处理的arguments,实现将类数组arguments转换为数组
var ary = Array.protopyte.slice.call(arguments);
ary=[].slice.call(arguments);
var aty = Array.prototype.slice.call(arguments);
ary.sort(function(a,b){
return a - b;
})
ary.shift();
ary.pop();
return (eval(ary.join("+"))/ary.lentth).toFixed(2);
var res = avgFn(9.8,9.7,10.,9.9,9.0,9.8,3.0);
console.log(res);
不将arguments转化为数组,所有用到数组的方法我们用call来实现
Array.prototype.sort.call(arguments.function(a,b){return a-b;});
[].shift.call(arguments);
[].pop.call(arguments);
return(eval([].join.call(arguments,"+"))/artuments.length).toFixed(2);