您的位置:首页 > Web前端 > JavaScript

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

2017-08-10 17:44 507 查看
思路:

将数组第一个元素当做最大(最小)值,存入变量;

遍历数组,依次与此变量比较,若大于(小于)变量,将此元素当做最大(最小)值存入变量;

返回此变量;

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()); //234
console.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);
}


(完)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript