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

重写Array.prototype.push时出现调用栈溢出错误求助

重写Array.prototype.push导致栈溢出的原因与解决办法

问题原因

你重写的push方法没有遵循原生Array.prototype.push的行为规范——原生push会返回数组的新长度,而你的自定义方法默认返回undefined。

当调用console.log(arr)时,JavaScript引擎的内部调试逻辑(比如构建数组的展示内容、遍历数组信息)会依赖push方法的返回值来完成流程。因为你的方法返回undefined,导致内部逻辑出现异常,进而无限递归调用你重写的push方法,最终触发Maximum call stack exceeded(栈溢出)错误。

而移除console.log(arr)后,没有触发这个依赖push返回值的内部逻辑,所以代码能正常执行。

解决办法

1. 对齐原生push的返回值

在自定义push方法末尾返回数组的新长度,和原生行为保持一致,就能解决栈溢出问题:

Array.prototype.push = function (ele) {
  this.length++;
  this[this.length - 1] = ele;
  console.log(ele);
  return this.length; // 返回新长度,对齐原生规范
};

const arr = [1, 2, 3];
arr.push(5);
console.log(arr); // 正常输出 [1, 2, 3, 5]

2. 避免污染全局Array原型

直接修改原生Array.prototype会影响所有数组实例,容易引发其他潜在问题。更稳妥的方式是不修改原型,改用自定义函数或子类实现需求:

// 方式一:自定义工具函数
function customPush(arr, ele) {
  arr.length++;
  arr[arr.length - 1] = ele;
  console.log(ele);
  return arr.length;
}

const arr = [1, 2, 3];
customPush(arr, 5);
console.log(arr);

// 方式二:创建Array子类
class CustomArray extends Array {
  push(ele) {
    super.push(ele); // 复用原生push的逻辑
    console.log(ele);
    return this.length;
  }
}

const customArr = new CustomArray(1, 2, 3);
customArr.push(5);
console.log(customArr);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:25:15