JavaScript 数组方法重写

发布时间 2023-12-21 17:27:13作者: 懒惰ing
const list = [1, 2, 3]

Array.prototype.myForeach = function (fn) {
    for (let i = 0; i < this.length; i++) {
        fn(this[i], i, this)
    }
}

Array.prototype.myMap = function (fn) {
    const _list = []
    for (let i = 0; i < this.length; i++) {
        _list.push(fn(this[i], i, this))
    }
    return _list
}

Array.prototype.myFilter = function (fn) {
    const _list = []
    for (let i = 0; i < this.length; i++) {
        !!fn(this[i], i, this) && _list.push(this[i])
    }
    return _list
}

Array.prototype.mySome = function (fn) {
    const _list = []
    for (let i = 0; i < this.length; i++) {
        if (!!fn(this[i], i, this)) {
            return true
        }
    }
    return false
}

Array.prototype.myFind = function (fn) {
    const _list = []
    for (let i = 0; i < this.length; i++) {
        if (!!fn(this[i], i, this)) {
            return this[i]
        }
    }
}

Array.prototype.myFindIndex = function (fn) {
    const _list = []
    for (let i = 0; i < this.length; i++) {
        if (!!fn(this[i], i, this)) {
            return i
        }
        return -1
    }
}

Array.prototype.myReverse = function (fn) {
    const _list = []
    for (let i = this.length - 1; i >= 0; i--) {
        _list.push(this[i])
    }
    return _list
}

Array.prototype.myReduce = function (fn, num) {
    let _num = num
    for (let i = 0; i < this.length; i++) {
        _num = fn(_num, this[i], i, this)
    }
    return _num
}