DIV CSS 佈局教程網

JavaScript 數組中獲取最大值與最小值的幾種方法
編輯:關於JavaScript     

獲取數組的最大值和最小值是使用頻率很高的操作,這裡整理幾種常見實現方式供大家參考,若有問題歡迎一起交流探討。

方法一:借助 reduce 實現

示例一,通過正則先校驗是否為合法數字,再用 reduce 遍歷比較:

 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; } }) } 

示例二,用 apply 把數組展開成參數傳給 Math:

 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"))

方法二:遍歷比較

用 for 循環逐一比對,直觀易懂:

 //最小值 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

apply 能指定調用對象並以數組形式傳入參數,正好契合 Math.max 的簽名:

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

還可以寫得更緊湊,直接掛到原型上支持鏈式調用:

 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 

三種方式各有側重:reduce 便於加入校驗邏輯,遍歷最直觀,而 apply 結合 Math 則最為簡潔高效。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved