萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JS 實現類 PHP in_array:判斷元素是否存在於陣列

JS 陣列原生缺少 in_array 方法,本文提供兩種擴展方案:原型鏈正則法與 jQuery 工具函數,並說明適用場景與注意事項。

方案一:擴展 Array.prototype(正則法)

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

原理:用特殊字符包裹每個元素轉為字串,再用正則匹配。限制:僅適用於字串/數字元素,對象/陣列會誤判。

方案二:jQuery $.inArray(標準迴圈法)

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 內部用 ==,可自行改為 ===)、無原型污染。

現代原生替代(ES2016+)

// includes 方法,語義最清晰
arr.includes('test'); // true
arr.includes(2);      // true
// 注意:includes 使用 SameValueZero 比較,NaN 也能匹配

建議

  • 現代項目優先用 Array.prototype.includes(IE 需 polyfill)。
  • 避免污染 Array.prototype,防止 for...in 遍歷出現意外屬性。
  • 若需索引位置,用 indexOf / findIndex。

選擇適合專案環境的方案,保持代碼乾淨。

copyright © 萬盛學電腦網 all rights reserved