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
    }
}

版权声明:本文为qq1154479896原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。