JS 陣列原生缺少 in_array 方法,本文提供兩種擴展方案:原型鏈正則法與 jQuery 工具函數,並說明適用場景與注意事項。
Array.prototype.S = String.fromCharCode(2); // 不可見分隔符
Array.prototype.in_array = function(e) {
var r = new RegExp(this.S + e + this.S);
return r.test(this.S + this.join(this.S) + this.S);
};
// 使用
var arr = ['b', 2, 'a', 4, 'test'];
console.log(arr.in_array('test')); // true
console.log(arr.in_array('c')); // false
原理:用特殊字符包裹每個元素轉為字串,再用正則匹配。限制:僅適用於字串/數字元素,對象/陣列會誤判。
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
// 使用
console.log($.inArray('test', arr)); // true
優點:語義清晰、支援嚴格相等 ===(jQuery 內部用 ==,可自行改為 ===)、無原型污染。
// includes 方法,語義最清晰
arr.includes('test'); // true
arr.includes(2); // true
// 注意:includes 使用 SameValueZero 比較,NaN 也能匹配
Array.prototype.includes(IE 需 polyfill)。Array.prototype,防止 for...in 遍歷出現意外屬性。indexOf / findIndex。選擇適合專案環境的方案,保持代碼乾淨。