取数组最大最小值得方法
一、
var arrays = [12,34,545,515,23,2,28];
//求最大值
function maxArr(arr){
return Math.max.apply(Math,arr);
}
//求最小值
function minArr(arr){
return Math.min.apply(Math,arr);
}
console.log(maxArr(arrays));//545
console.log(minArr(arrays));//2
二、
//原型方法求最大
function arr_max(){
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.max = arr_max;
var arr1 = new Array(12,34,545,515,23,2,28);
var arr2 = arr1.max();
console.log(arr2);//545
//原型方法求最小
function arr_min(){
var min = this[0];
var len = this.length;
for(var i = 1;i < len;i++){
if(this[i] < min){
min = this[i];
}
}
return min;
}
Array.prototype,min = arr_min;
var arr3 = new Array(12,34,545,515,23,2,28);
var arr4 = arr3.min();
console.log(arr4);//2
欢迎各位朋友补充