js手写 map和foreach

map函数接收两个参数

1 迭代器函数 ,该函数有三个参数

  • 数组项的值
  • 数组项下标
  • 数组对象本身

2 迭代器函数的this指向
(注:当传了该值,迭代器函数不能为箭头函数了。原因是箭头函数没有this隐式指向。箭头函数在定义时候就已经绑定了上层上下文中非箭头函数this)

Array.prototype.MyMap = function (fn, toThis) {
    if (!Array.isArray(this)) {
        throw new Error(this + 'is not a array')
    }
     // Object.create(null)没有继承任何原型方法,也就是说它的原型链没有上一层。
    const redirectThis = toThis || Object.create(null)
    let arr = this
    let newArr = []
    for (let i = 0; i < arr.length; i++) {
        // call的意思是继承  将 fn被传入的方法放在toThis执行, 后面的是方法的参数
        newArr.push(fn.call(toThis, arr[i], i , arr))
    }
    return newArr
}

var a = [1, 2, 3, 4]
const b = a.MyMap((el, i) => el * el)
console.log(b)

手写forEach
1.参数
数组的每一项,数组的下标,数组本身
2.thisArg 可选
可选参数。当执行回调函数 callback 时,用作 this 的值。

Array.prototype.MyForEach = function(fn, thisArg) {
    const arr = this
    if (typeof fn !== "function") {
     throw "参数必须为函数";
    }
    if (!Array.isArray(arr)) {
     throw "只能对数组使用forEach方法";
    }
    const redirectThis = toThis || Object.create(null)
    for (let index = 0; index < arr.length; index++) {
     fn.call(redirectThis, arr[index], index, arr);
    }
}
var arr1 = [1, 2, 3, 4]
arr1.MyForEach((el, index) => {
    console.log(el, index)
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值