Javascript擷取數組中的最大值和最小值的方法匯總,javascript數組

來源:互聯網
上載者:User

Javascript擷取數組中的最大值和最小值的方法匯總,javascript數組

比較數組中數值的大小是比較常見的操作,比較大小的方法有多種,比如可以使用內建的sort()函數,下面來介紹如下幾種方法,代碼如下:

方法一:

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

方法三:

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"));//10console.log(getMaximin(b,"min"));//04

方法四:

var a=[1,2,3,5];alert(Math.max.apply(null, a));//最大值alert(Math.min.apply(null, a));//最小值

多維陣列可以這麼修改:

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

以上內容是小編給大家分享的Javascript擷取數組中的最大值和最小值的方法匯總,希望大家喜歡。

您可能感興趣的文章:
  • js數字輸入框(包括最大值最小值限制和四捨五入)
  • JS擷取隨機數函數可自訂最小值最大值
  • JavaScript擷取數組最小值和最大值的方法
  • JavaScript如何擷取數組最大值和最小值
  • JS擷取數組最大值、最小值及長度的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.