在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.
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.
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

