不能清空数组扩展 class 的元素

Can't empty Array extended class's elements

我正在尝试通过扩展本机数组来制作自定义数组 class,但我不知道如何清空元素,这是我的尝试。

class MyArray extends Array {
  // for simplicity I just included the bit of code that fails.
  reset () {
    this = []; // fails of course
  }
}

const myarray = new MyArray();
myarray.push(1);
myarray.reset(); // fails because it tries to rewrite `this`

我做错了什么?

将数组长度设置为零将删除所有元素。

class MyArray extends Array {
  // for simplicity I just included the bit of code that fails.
  reset () {
    this.length = 0;
  }
}

const myarray = new MyArray();
myarray.push(1,2,3,4);

console.log('before', myarray);
myarray.reset();
console.log('after', myarray);

有关清空数组的更多方法,请参见How do I empty an array in JavaScript?

接受的答案中提到了此方法:

Method 2 (as suggested by Matthew Crumley)

A.length = 0

This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.

您可以使用splice

class MyArray extends Array {
  // for simplicity I just included the bit of code that fails.
  reset () {
    this.splice(0, this.length);
  }
}

const myarray = new MyArray();
myarray.push(...[1,2,3,4]);

console.log('before', myarray);
myarray.reset();
console.log('after', myarray);