美文网首页
Array.prototype.indexOf

Array.prototype.indexOf

作者: 玲儿珑 | 来源:发表于2021-03-23 08:12 被阅读0次

源码实现如下:

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)

相关文章

网友评论

      本文标题:Array.prototype.indexOf

      本文链接:https://www.haomeiwen.com/subject/rdpxhltx.html