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

在Array.prototype上创建修改原数组的empty方法报错,求解决方案

Ah, I see the issue here! Let's break down why that line throws an error and how to fix it properly.

Why this = [] Throws an Error

In JavaScript, this is a special keyword that refers to the current object (in this case, the array instance calling empty()). Unlike regular variables, you can't reassign this—it's not a mutable reference you can overwrite. When you try to do this = [], the interpreter throws a syntax error because this assignment is invalid.

Think of it this way: this points to the existing array object in memory. You can't make it point to a brand new empty array; instead, you need to modify the existing array to be empty.

The Fix: Modify the Existing Array

There are a couple of clean, efficient ways to empty the original array without trying to reassign this:

Method 1: Set length to 0

This is the simplest and fastest approach. In JavaScript, setting an array's length to 0 directly truncates all elements, modifying the original array:

Array.prototype.empty = function() {
  this.length = 0;
};

Test it out:

var arr = [1, 3];
arr.empty();
console.log(arr); // Output: []

Method 2: Use splice()

The splice() method modifies the array in place. Calling splice(0) removes all elements starting from index 0:

Array.prototype.empty = function() {
  this.splice(0);
};

This works just as well—though length = 0 is generally considered more performant for emptying arrays.

Why These Work

Both methods modify the existing array object that this refers to, rather than trying to replace this with a new array. That's exactly what you need for a mutating method that changes the original array.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:48:11