JavaScript数组最大值、最小值和平均数
分类:实例代码
JavaScript数组最大值、最小值和平均数属于前端实例代码,有关更多实例代码大家可以查看。
本章节介绍一下如何获取javascript数值数组中的最大值、最小值和平均数。
这几个功能在很多实际应用中是经常用到的。
代码实例如下:
function cacl(arr, callback) { var ret; for (var index=0; index<arr.length;index++) { ret = callback(arr[index], ret); } return ret; } Array.prototype.max = function () { return cacl(this, function (item, max) { if (!(max > item)) { return item; } else { return max; } }); }; Array.prototype.min = function () { return cacl(this, function (item, min) { if (!(min < item)) { return item; } else { return min; } }); }; Array.prototype.sum = function () { return cacl(this, function (item, sum) { if (typeof (sum) == 'undefined') { return item; } else { return sum += item; } }); }; Array.prototype.avg = function () { if (this.length == 0) { return 0; } return this.sum(this) / this.length; }; var theArray=[1,-2,4,9,15]; console.log(theArray.max()); console.log(theArray.min()); console.log(theArray.sum()); console.log(theArray.avg());
代码相对比较简单,更多内容参阅相关阅读:
相关阅读:
(1).prototype参阅JavaScript prototype 原型一章节。
(2).typeof参阅JavaScript typeof 运算符一章节。
JavaScript数组最大值、最小值和平均数,这样的场景在实际项目中还是用的比较多的,关于JavaScript数组最大值、最小值和平均数就介绍到这了。