常用indexOf一般是针对String类型,在ECMA-262 标准 的第5版中增加了数组的indexOf方法,因此,Array.indexOf存在兼容性问题。Array.indexOf和String.indexOf用法一致。当需要兼容Array.indexOf时,可以自己polyfill。
代码来自:MDN
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n