手写map,filter,some,every方法

手写map,filter,some,every方法

map方法

map用于遍历数组

//原型对象中的this指向实例出来的对象
 [].__proto__.myMap = function (callback) {
            for (let index = 0; index < this.length; index++) {
                callback(this[index], index, this)
            }
        }
        const arr = [1,3,5,7]
        const res = arr.myMap((item, index) => {
            console.log(item, index);
        })

filter方法

filter主要用于筛选出满足条件的元素,返回一个新数组

[].__proto__.myFliter = function (callback) {
            const newArr = []
            for (let index = 0; index < this.length; index++) {
            //返回值为真,就说明满足条件,就添加到新数组中
                const flag = callback(this[index], index)
                if (flag) {
                    newArr.push(index)
                }
            }
            return newArr
        }
        const arr = [1, 2, 3, 4, 5, 6, 7]
        const res = arr.filter(item => item > 5)
        console.log(res);

some方法

some用来判断数组中只要有一个元素满足就返回为true,否则返回false

[].__proto__.mySome = function (callback) {
            for (let index = 0; index < this.length; index++) {
            //如果返回值为真,就说明满足条件,就返回true
                if (callback(this[index], index, this)) return true
            }
            return fasle
        }

        const arr = [1, 2, 3]
        const res = arr.some(item => item % 2 === 0)
        console.log(res);

every方法

every遍历数组,所有元素都满足条件才返回true,否则返回false

[].__proto__.myEvery = function (callback) {
            let falg = null
            for (let index = 0; index < this.length; index++) {
                flag = callback(this[index])
                //只要有一个返回值为假,就返回false,
                if (!flag) return false
            }
            //否则返回true
            return true
        }
        const arr = [2, 4, 6, 1]
        const res = arr.myEvery(item => item % 2 === 0)
        console.log(res);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

史蒂文·月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值