「包含」判斷幾乎是每個項目都會用到的操作。可以給 String 對象擴展一個 contains 方法,讓判斷寫起來更貼近自然語言。
// 老舊環境下先補上 Array.prototype.indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) {
return i;
}
}
return -1;
};
}
if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg); // 找到返回索引,取反兩次轉為布爾值
};
}
這裡的 !!~ 是個小技巧:~ 是按位取反,indexOf 返回 -1 時 ~(-1) 為 0(假值),返回 0 時 ~0 為 -1(真值),再套兩個 ! 就得到規範的布爾結果。
Enter two strings and check if String 1 contains String 2.<br> <br>
String 1: <input id="foo" type="text" value="a quick brown fox jumps over"><br>
String 2: <input id="bar" type="text" value="fox jumps"><br><br>
<button onclick="checkstring()">Click to check if String 1 contains String 2</button>
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
};
}
if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}
function checkstring() {
var foo = document.getElementById("foo").value;
var bar = document.getElementById("bar").value;
alert(foo.contains(bar));
}
</script>
ES2015 已經內建了標準方法 String.prototype.includes,語意與此處完全一致:
'a quick brown fox'.includes('fox'); // true
需要區分大小寫時用它即可;若要忽略大小寫,可以先 toLowerCase() 再比較,或者直接使用正則表達式並帶上 i 標誌。相比擴展原型,優先使用標準 API 能避免與其他庫的實現發生衝突。