JavaScript去除數組中的重複值

來源:互聯網
上載者:User

用原型函數(prototype)可以定義一些很方便的自訂函數,實現各種自訂功能。

Javascript 中的原型函數(prototype)的工作原理,在 javascript 中每次聲明新函數的過程中,就會為其建立一個 prototype 的屬性。在未加其他附帶條件情況下,所有的 prototype 屬性都會自動擷取 constractor 屬性,constructor 內包含一個指向 prototype 屬性所屬函數的指標(就是說 constructor 回指建構函式本身)。

舉個例子來說,Fruit.prototype.constructor 指向 Fruit。並且可以通過這個建構函式,為其添加更多的屬性和方法。

當調用建構函式建立一個新執行個體後,該執行個體內部包含一個指標指向建構函式的原型函數。此時我們不用去關心內部的這個指標到底是什麼(這個指標還的確有個名字:__proto__ 估計是為了對應 prototype 而起的名字吧 ~\(≧▽≦)/~ ),只需記住它的指向即可(指向建構函式的原型函數)。需要注意的是,這個 __proto__ 只存在於函數執行個體與建構函式的原型函數之間,而非執行個體與建構函式之間。

下面是使用 prototype 自訂了3個函數,分別是去掉數組中的重複值,還有求數組中的最大值與最小值。

數組定義為: var arr = [2,1,3,2,1,4,3,4,2,1];

程式碼為:

<script type="text/javascript">Array.prototype.unique = function(){     var a = {};     var len = this.length;     for(var i=0; i < len; i++)  {         if(typeof a[this[i]] == "undefined")         a[this[i]] = 1;       }       this.length = 0;       for(var i in a)       this[this.length] = i;       return this;     }  Array.prototype.max = function(){   //最大值 return Math.max.apply({},this) }Array.prototype.min = function(){   //最小值 return Math.min.apply({},this) }var arr = [2,1,3,2,1,4,3,4,2,1];var btn1 = document.getElementById("btn1");btn1.onclick = function(){arr.unique();alert(arr.toString());}var btn2 = document.getElementById("btn2");btn2.onclick = function(){alert(arr.max());}var btn3 = document.getElementById("btn3");btn3.onclick = function(){alert(arr.min());}</script>

聯繫我們

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