本文透過擴充 Array 的 prototype 定義一個 contains 方法,如此一來任何陣列都能直接呼叫它來判斷是否包含某個元素。
/**
* Array.prototype.[method name] 允許你定義或覆寫物件的方法
* needle 是你搜尋的項目
* this 是一個特殊變數,指向目前這個 Array 實例
* 若 needle 存在於陣列中則回傳 true,否則回傳 false
*/
Array.prototype.contains = function ( needle ) {
for (i in this) {
if (this[i] == needle) return true;
}
return false;
}
使用方式:
// 現在你可以這樣做:
var x = Array();
if (x.contains('foo')) {
// do something special
}
透過在原型上掛上 contains 方法,就能讓判斷語句寫得更直覺易讀。