获取平均数之Function.prototype.call()、Function.prototype.apply()应用

// = > 1、常规方法:

function sum(arg) { var newary = []; //类数组转换为数组 if (arg instanceof Array){ console.log("传参方式是数组"); for (var i = 0; i < arg.length; i++) { newary.push(arg[i]); } }else { console.log('传参方式是多个数字'); for (var i = 0; i < arguments.length; i++) { newary.push(arguments[i]); } }//数组从小到打排序 newary.sort(function (a,b) { return a-b; }); //删除数组开头的最小项 newary.shift(); //删除数组末尾最大项 newary.pop(); //循环求和 var result= 0; for (var i = 0; i < newary.length; i++) { result += newary[i]; } //求平均数,并返回结果 return Math.round(result/newary.length); }var result1 = sum(156,423,90,5,24,66,450,25,4,86,76,64,5,88,63,33,42,34,46,19,48,35,70); console.log(result1); // => 71.33333333333333var arr = [1,2,3,4,5,6,7,8,9]; var result2 = sum(arr); console.log(result2); // => 5

// = > 常规方法改进:1.0版
function sum(arg) { //类数组转换为数组 if (arg instanceofArray) { var newary =Array.prototype.slice.apply(arg); }else { var newary =Array.prototype.slice.call(arguments); } //数组从小到打排序 newary.sort(function (a,b) { return a-b; }); //删除数组开头的最小项 newary.shift(); //删除数组末尾最大项 newary.pop(); //求平均数,并返回结果 return (eval(newary.join('+'))/newary.length).toFixed(2) }var result1 = sum(156,423,90,5,24,66,450,25,4,86,76,64,5,88,63,33,42,34,46,19,48,35,70); console.log(result1); // = >71.33var arr = [1,2,3,4,5,6,7,8,9]; var result2 = sum(arr); console.log(result2); // = >5.00

【获取平均数之Function.prototype.call()、Function.prototype.apply()应用】// = > 常规方法改进:2.0版
function sum(arg) { console.log(arg instanceof Array); if (!(arg instanceof Array)) { console.log("如果不是数组,执行下面语句"); var newary = Array.prototype.sort.call(arguments, function (a,b) {return a - b; }); } else { console.log("如果是数组,执行下面语句"); var newary = Array.prototype.sort.apply(arguments[0],function (a,b) { return a-b; }); } //删除数组开头的最小项 Array.prototype.shift.call(newary); //删除数组末尾最大项 Array.prototype.pop.call(newary); //求平均数,并返回结果 return (eval([].join.call(newary,'+')) / newary.length).toFixed(2) }var result1 = sum(156, 423, 90, 5, 24, 66, 450, 25, 4, 86, 76, 64, 5, 88, 63, 33, 42, 34, 46, 19, 48, 35, 70); console.log(result1); // => 71.33var arr = [1,2,3,4,5,6,7,8,9]; var result2 = sum(arr); console.log(result2); //=>5.00

    推荐阅读