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

自定义Array.prototype.clear方法时赋值this报错,求可行解决方案

Array.prototype.clear的可行实现方案

你原来的代码报错是因为this在函数里是只读引用,没法直接赋值成新数组。下面几种方案都是直接修改原数组,不会创建新对象,完全符合你的需求:

  • 修改length属性(最简单高效)
    数组的length属性是可写的,直接设为0就能清空所有元素:

    function clear() {
      this.length = 0;
    }
    Object.defineProperty(Array.prototype, 'clear', { value: clear, enumerable: true });
    
  • 使用splice方法
    调用splice(0)会从数组起始位置删除所有元素,同样是在原数组上修改:

    function clear() {
      this.splice(0);
    }
    Object.defineProperty(Array.prototype, 'clear', { value: clear, enumerable: true });
    
  • 循环删除元素(不推荐,效率较低)
    通过pop()逐个移除末尾元素,直到数组为空,适合理解原理但实际用前两种更优:

    function clear() {
      while (this.length > 0) {
        this.pop();
      }
    }
    Object.defineProperty(Array.prototype, 'clear', { value: clear, enumerable: true });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:35:19