You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改JavaScript中Array.push方法触发TypeError,如何解决?

问题描述

尝试给JavaScript里的Array.push方法加额外功能,运行下面代码时触发了TypeError错误:

let array = [];

const oldPushMethod = array.push;

array.push = (el) => {
    console.log(el);
    oldPushMethod(el);
}

array.push(10);

错误提示:

Uncaught TypeError: Cannot convert undefined or null to object
at push ()

问题原因

核心问题是this指向异常:

  • 把array.push提取成变量oldPushMethod后,直接调用它时,内部的this不再指向原数组array,而是变成了全局对象(严格模式下是undefined),但push方法必须依赖this指向数组对象才能正常工作,因此抛出错误。
  • 另外你用了箭头函数重写array.push,箭头函数没有自己的this,会继承外层作用域的this,这也会导致后续调用时this不符合预期。
解决方案

方案1:用普通函数+call/apply绑定this

把箭头函数改成普通函数,调用原push方法时用call绑定当前数组作为this:

let array = [];

const oldPushMethod = array.push;

array.push = function(el) {
    console.log(el);
    oldPushMethod.call(this, el);
}

array.push(10); // 输出10,array变为[10]

方案2:预先用bind绑定this到原数组

如果一定要用箭头函数,提前把oldPushMethod的this绑定到array:

let array = [];

const oldPushMethod = array.push.bind(array);

array.push = (el) => {
    console.log(el);
    oldPushMethod(el);
}

array.push(10); // 输出10,array变为[10]

扩展:支持多参数的push

原生push可以一次添加多个元素,若要保留这个功能,可以改成下面这样:

let array = [];

const oldPushMethod = array.push;

array.push = function(...args) {
    console.log('要添加的元素:', args);
    return oldPushMethod.apply(this, args); // 返回push的返回值(数组新长度)
}

array.push(10, 20, 30); // 输出"要添加的元素: [10,20,30]",array变为[10,20,30]

内容的提问来源于stack exchange,提问作者Vishal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:52:20