js 中 Array 常用方法原理

经常会忘记数组的方法,因此将常用的方法用js实现,通过实现原理来加深印象

	let a = [1, 2, 3]
	// 1维数组深拷贝
	let [...b] = a
	let c = a.concat()
	let d = a.slice(0)
function deepCopy(target) {
    let result

    const type = typeof target
    if (type === 'object') {
        if (target === null) return target
        if (Array.isArray(target)) return target.map(item => deepCopy(item))
        result = {}
        for (let key in target) {
            result[key] = deepCopy(target[key])
        }
    } else {
        result = target
    }
    return result
}

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

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

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

// 在使用reduce 时,第三个参数(index)从1开始  
Array.prototype.myReduce = function(fn, init) {
    let res
    for (let i = 0; i < this.length; i++) {
        if (i === 0) {
            res = !init ? this[0] : fn(init, this[i], i)
        } else {
            res = fn(res, this[i], i)
        }
    }
    return res
}


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


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


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

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

Array.prototype.myIndexOf = function(element, fromIndex) {

    const len = this.length
    if (typeof fromIndex !== 'number') fromIndex = 0
    if (fromIndex < 0) fromIndex = len - fromIndex

    for (let i = fromIndex; i < len; i++) {
        if (element === this[i]) return i
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值