Javascript apply的巧妙用法

來源:互聯網
上載者:User

標籤:blog   border   property   最小   uri   code   沒有   prot   console   

Math.max 可以實現得到數組中最大的一項
var array = [1,2,3,4,5];var max = Math.max.apply(null, array);console.log(max); // 5

調用的時候第一個參數給了一個null,這個是因為沒有對象去調用這個方法,只需要用這個方法協助運算,得到返回的結果就行,所以直接傳遞了一個null過去。

Math.min 可以實現得到數組中最小的一項
var array = [1,2,3,4,5];var min= Math.min.apply(null, array);console.log(min); // 1
在原生對象上面添加max與min方法

那就會需要用到原生對象方法Object.defineProperty()方法會直接在一個對象上定義一個新屬性,或者修改一個對象的現有屬性, 並返回這個對象。

在原生對象上面添加方法,for迴圈也會尋找不到

    Object.defineProperty(Array.prototype, ‘max‘, {          writable: false,          enumerable: false,          configurable: true,          value: function () {              return Math.max.apply(null, this);          }      });            Object.defineProperty(Array.prototype, ‘min‘, {          writable: false,          enumerable: false,          configurable: true,          value: function () {              return Math.min.apply(null, this);          }      });  

如何使用呢,直接在數組上調用即可

var arr = [54,545,2165,545,56];  console.log(arr.max());  console.log(arr.min()); 

 

Javascript apply的巧妙用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.