現在獲取數組中最大最小值用的越來越多了,於是乎我編了個方法供大家使用。代碼如下,若有問題可以與我聯系,咱們一起學習一起進步。
我們來看下示例一:
var numReg = /^-?[0-9]+.?[0-9]*$/
Array.prototype.min = function() {
return this.reduce(function(preValue, curValue,index,array) {
if ( numReg.test(preValue) && numReg.test(curValue) ) {
return preValue > curValue ? curValue : preValue;
} else if ( numReg.test(preValue) ) {
return preValue;
} else if ( numReg.test(curValue) ) {
return curValue;
} else {
return 0;
}
})
}
Array.prototype.max = function() {
return this.reduce(function(preValue, curValue,index,array) {
if ( numReg.test(preValue) && numReg.test(curValue) ) {
return preValue < curValue ? curValue : preValue;
} else if ( numReg.test(preValue) ) {
return preValue;
} else if ( numReg.test(curValue) ) {
return curValue;
} else {
return 0;
}
})
}
示例二:
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]
alert("aMax:" + getMaximin(a,"max") + "---aMin:" + getMaximin(a,"min") + "---bMax:" + getMaximin(b,"max") + "---bMin:" + getMaximin(b,"min"))//aMax:10---aMin:2---bMax:786---bMin:4
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]
alert("aMax:" + getMaximin(a,"max") + "---aMin:" + getMaximin(a,"min") + "---bMax:" + getMaximin(b,"max") + "---bMin:" + getMaximin(b,"min"))//aMax:10---aMin:2---bMax:786---bMin:4
我們再來看2個方法
方法一:
//最小值
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.max = function( array ){
return Math.max.apply( Math, array );
};
Array.min = function( array ){
return Math.min.apply( Math, array );
};
但是,John Resig是把它們做成Math對象的靜態方法,不能使用大神最愛用的鏈式調用了。但這方法還能更精簡一些,不要忘記,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