要重写Array.forEach函数自身,需要使用原型链来修改Array.prototype.forEach方法。下面是一个示例代码:
// 保存原始的Array.prototype.forEach方法
const originalForEach = Array.prototype.forEach;
// 重写Array.prototype.forEach方法
Array.prototype.forEach = function(callback, thisArg) {
// 调用原始的forEach方法
originalForEach.call(this, callback, thisArg);
// 在这里添加你的自定义代码
// 例如,将每个元素转换为大写并输出到控制台
this.map((item) => {
console.log(item.toUpperCase());
});
};
// 使用重写后的forEach方法
const arr = ['apple', 'banana', 'orange'];
arr.forEach((item) => {
console.log(item); // 输出原始数组的元素
});
在这个示例中,我们保存了原始的Array.prototype.forEach方法,并用自定义的forEach方法来替换它。在自定义的forEach方法中,我们首先调用了原始的forEach方法,确保它的原始功能不受影响。然后,在自定义代码部分,我们将每个元素转换为大写并输出到控制台。
最后,我们使用重写后的forEach方法来遍历数组,并观察到数组元素被转换为大写并输出到控制台。