不能清空数组扩展类的元素
我正在尝试通过扩展本机 Array 来创建自定义 Array 类,但我不知道如何清空元素,这是我的尝试。
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);
请参阅如何在 JavaScript 中清空数组?有关清空数组的更多方法。
接受的答案中提到了此方法:
方法 2(由Matthew Crumley建议)
A.length = 0这将通过将其长度设置为 0 来清除现有数组。有人认为这可能不适用于 JavaScript 的所有实现,但事实证明并非如此。它也适用于在 ECMAScript 5 中使用“严格模式”,因为数组的长度属性是一个读/写属性。