JavaScript 的原生數組沒有 contains 方法,判斷某個值是否存在時總要多寫幾行,用起來不太順手。其實實現起來非常簡單。
function contains(a, obj) {
var i = a.length;
while (i--) { // 從尾往前遍歷
if (a[i] === obj) {
return true;
}
}
return false;
}
把方法掛到 Array.prototype 上,調用起來就自然多了:
Array.prototype.contains = function (obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
};
alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false
第二行的結果值得留意:這裡用的是嚴格相等 ===,數字 2 與字符串 '2' 被視為不同的值。如果希望做寬鬆比較,把 === 換成 == 即可。
在今天的項目裡,其實不太需要自己擴展原型了。ES5 起,數組自帶的 indexOf 就能勝任:
[1, 2, 3].indexOf(2) !== -1; // true
ES2016 之後更有語意清晰的 includes:
[1, 2, 3].includes(2); // true
之所以不建議修改內建原型,是因為它可能被第三方庫覆蓋,也容易在 for...in 遍歷時意外枚舉出來。理解原理之餘,工程中優先選用標準方法會更省心。