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

如何改写JavaScript数组remove扩展方法实现pop式行为?

实现修改原数组的Array.prototype.remove方法

要让Array.prototype.remove像pop那样修改原数组并返回被删除元素,直接利用数组原生的splice方法就能实现——splice本身会修改原数组,还会返回被删除元素组成的数组。具体实现如下:

Array.prototype.remove = function(index) {
  // 处理非法索引:索引小于0、超出数组长度,或不是数字时返回undefined
  if (index < 0 || index >= this.length || typeof index !== 'number') {
    return undefined;
  }
  // splice删除指定索引的1个元素,返回被删元素组成的数组,取第一个元素返回
  return this.splice(index, 1)[0];
};

测试验证

用题目给出的示例测试:

let arr = [0, 1, 2, 3, 4, 5];
let removed = arr.remove(3);
console.log({arr, removed}); // 输出:{ arr: [0, 1, 2, 4, 5], removed: 3 }

补充说明

  • 方法里的this指向调用该方法的数组实例,符合原型方法的标准写法
  • 加入索引合法性校验,是为了和数组原生方法的行为保持一致(比如pop在空数组返回undefined,at越界也返回undefined)
  • splice(index, 1)表示从index位置开始删除1个元素,返回的数组里只有被删除的那个元素,所以取[0]就能拿到要返回的值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:35:59