gpt4 book ai didi

javascript - 不能清空数组扩展类的元素

转载 作者:行者123 更新时间:2023-12-05 09:35:17 28 4
gpt4 key购买 nike

我正在尝试通过扩展 native 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);

参见 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.

关于javascript - 不能清空数组扩展类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65942230/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com