IE 8 và cũ hơn không hỗ trợ Array.prototype.indexOf. Cần polyfill hoặc dùng thư viện jQuery $.inArray().
Polyfill chuẩn (ES5)
// Thêm vào đầu trang (trước code khác)
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
if (this == null) throw new TypeError('"this" is null or not defined');
const o = Object(this);
const len = o.length >>> 0;
if (len === 0) return -1;
const n = fromIndex | 0;
let k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) return k;
k++;
}
return -1;
};
}
Dùng jQuery.inArray (nếu đã có jQuery)
// jQuery.inArray(value, array [, fromIndex])
// Trả về index hoặc -1
var idx = $.inArray('value', myArray);
Conditional Comment cho IE (cách cũ)
<!--[if lte IE 8]> <script src="polyfill-indexof.js"></script> <![endif]-->
Lưu ý
- IE 9+ đã hỗ trợ
indexOfgốc. - Polyfill trên tuân thủ spec ES5 (xử lý sparse array, fromIndex âm, v.v.).
- Hiện nay (2024) không còn cần hỗ trợ IE – có thể bỏ polyfill.