手写js数组方法:some、every、filter、find、forEach、map、sort

  1. some : 有一个满足条件则返回true,并停止遍历
Array.prototype.mySome = function(fn) {
    for(let i = 0; i < this.length; i++) {
        if(fn(this[i])) return true
    }
    return false
}
const handArr = [1,2,3,4,5]
const is = handArr.mySome((item) => {
    return item < 4
})
console.log(is)
  1. every :全部满足则返回true
Array.prototype.myEvery = function(fn) {
    for(let i = 0; i < this.length; i++) {
        if(!fn(this[i])) return false
    }
    return true
}
const handArr = [1,2,3,4,5]
const is = handArr.myEvery((item) => {
    return item < 6
})
console.log(is)
  1. filter :返回满足条件的数组
Array.prototype.myFilter = function(fn) {
    const arr = []
    for(let i = 0; i < this.length; i++) {
        if(fn(this[i])) arr.push(this[i])
    }
    return arr
}
const handArr = [1,2,3,4,5]
const is = handArr.myFilter((item) => {
    return item < 3
})
console.log(is)
  1. find :返回第一个符合条件的值,并停止遍历
Array.prototype.myFind = function(fn) {
    for(let i = 0; i < this.length; i++) {
        if(fn(this[i])) return this[i]
    }
    return undefined
}
const handArr = [1,2,3,4,5]
const is = handArr.myFilter((item) => {
    return item < 4
})
console.log(is)
  1. forEach :遍历
Array.prototype.myForEach = function(fn) {
    for(let i = 0; i < this.length; i++) {
        // arr[i] = fn(this[i])
        fn.call('window', this[i], i, this)
    }
}
const handArr = [1,2,3,4,5]
handArr.myEvery((item) => {
    console.log(item)
})
  1. map :返回计算之后的新数组
Array.prototype.myMap = function(fn) {
    const arr = []
    for(let i = 0; i < this.length; i++) {
        // arr[i] = fn(this[i])
        arr[i] = fn.call('window', this[i], i, this)
    }
    return arr
}
const handArr = [1,2,3,4,5]
const is = handArr.myMap((item) => {
    return item * 2
})
console.log(is)
  1. sort :冒泡排序
Array.prototype.mySort = function(fn) {
    for(let i = 0; i < this.length; i++) {
        for(let j = 0; j < this.length - i; j++){
            if(fn(this[j], this[j+1]) > 0) {
                // let temp = this[j]
                // this[j] = this[j+1]
                // this[j+1] = temp
                [this[j+1], this[j]] = [this[j], this[j+1]] //利用ES6解构交换两个数,更简单
            }
        }
    }
    return this
}

const handArr = [1,3,5,2,4]
const is = handArr.mySort((a, b) => {
    return a-b
})
console.log(is)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值