源码实现如下:
if (!Array.prototype.myIndexOf) {
Array.prototype.myIndexOf = function ( searchElement, fromIndex ) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
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;
}
}
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]
arr.indexOf(4)
网友评论