JavaScript获取数组中最大(最小)值

来源:互联网 发布:四川广电网络投诉电话 编辑:程序博客网 时间:2024/06/06 21:31

思路:

  1. 将数组第一个元素当做最大(最小)值,存入变量;
  2. 遍历数组,依次与此变量比较,若大于(小于)变量,将此元素当做最大(最小)值存入变量;
  3. 返回此变量;
var arr = [1, 45, 23, 3, 6, 2, 7, 234, 56];
//最大值Array.prototype.max = function() {    var max = this[0];    var len = this.length;    for (var i = 1; i < len; i++) {        if (this[i] > max) {            max = this[i];        }    }    return max;}//最小值Array.prototype.min = function() {    var min = this[0];    var len = this.length;    for (var i = 1; i < len; i++) {        if (this[i] < min) {            min = this[i];        }    }    return min;}

测试如下

console.log(arr.max()); //234console.log(arr.min()); //1

用forEach()方法改写上面的代码:(for循环性能要比forEach()差)

Array.prototype.max = function (){    var max = this[0];    this.forEach (function(ele,index,arr){        if(ele > max) {            max = ele;        }    })    return max;}Array.prototype.min = function (){    var min = this[0];    this.forEach (function(ele,index,arr){        if(ele < min) {            min = ele;        }    })    return min;}

用reduce()方法改写上面的代码

reduce()方法可以接收一个回调函数callbackfn,可以在这个回调函数中拿数组中的初始值(preValue)与数组中当前被处理的数组项(curValue)做比较,如果preValue大于curValue值返回preValue,反之返回curValue值

Array.prototype.max = function() {    return this.reduce(function(preValue, curValue,index,array) {        return preValue < curValue ? curValue : preValue;    })}Array.prototype.min = function() {    return this.reduce(function(preValue, curValue,index,array) {        return preValue > curValue ? curValue : preValue;    })}

用Math 对象的Math.max()和Math.min()方法

Array.prototype.max = function () {    return Math.max.apply({},this);}Array.prototype.min = function () {    return Math.min.apply({},this);}

(完)