前端·如何手写一个forEach函数

159 阅读1分钟
const arr = [
    { name: 'A', english: 98, math: 80},
    { name: 'B', english: 90, math: 81},
    { name: 'c', english: 88, math: 90},
    { name: 'D', english: 99, math: 110}
];

arr.forEach((item) => {
    return item.total = item.english + item.math;
})

console.log(arr);

image.png

1.如何写出自己一个具有forEach功能的api

// 手写forEach函数
Array.prototype.sdk_forEach = function (cb) {
    let context = arguments[1];
    if(cb instanceof Function) {
        for(let i = 0; i < this.length; i++) {
            cb.call(context,this[i], i, this)
        }
    } else {
        throw new Error(`${sdk_forEach} is not a function`)
    }
}

arr.sdk_forEach((item) => {
    return item.total = item.english + item.math;
})
console.log(arr);

50a04c8b8350839faa97b45ed9d3b98.png

2.这样我们得到一个跟forEach函数具有一样的功能