1. 程式人生 > >Js獲取陣列中的最大值和最小值

Js獲取陣列中的最大值和最小值

方法一:在陣列的原型上加方法
//最小值
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;
}
//最大值
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;
}

如果你是引入類庫進行開發,害怕類庫也實現了同名的原型方法,可以在生成函式之前進行重名判斷
if (typeof Array.prototype[‘max’] == ‘undefined’) {
Array.prototype.max = function() {
… …
}
}

方法二:用Math.max和Math.min方法可以迅速得到結果。apply能讓一個方法指定呼叫物件與傳入引數,並且傳入引數是以陣列形式組織的。恰恰現在有一個方法叫Math.max,呼叫物件為Math,與多個引數
Array.prototype.max = function(){
return Math.max.apply({},this)
}
Array.prototype.min = function(){
return Math.min.apply({},this)
}
[1,2,3].max()// => 3
[1,2,3].min()// => 1

方法三:
function getMaximin(arr,maximin)
{
if(maximin==”max”)
{
return Math.max.apply(Math,arr);
}
else if(maximin==”min”)
{
return Math.min.apply(Math, arr);
}
}
var a=[3,2,4,2,10];
var b=[12,4,45,786,9,78];
console.log(getMaximin(a,”max”));//10
console.log(getMaximin(b,”min”));//04

方法四:
var a=[1,2,3,[5,6],[1,4,8]];
var ta=a.join(“,”).split(“,”);//轉化為一維陣列
alert(Math.max.apply(null,ta));//最大值
alert(Math.min.apply(null,ta));//最小值

方法 五:利用擴充套件操作符,直接用Math.max和Math.min
var a=[3,2,4,2,10];
console.log(Math.min(…a)); //2