我正在尝试创建 javascript 数组的子类。我想使用数组类型参数启动子类,并添加一个方法来从数组(子类)中删除元素。
我的代码如下所示:
class CustomArray extends Array {
constructor(array) {
console.log('Initiating array:', array)
super(...array);
}
remove(element) {
let index = this.indexOf(element);
if (index > -1) {
return this.splice(index, 1);
}
return [];
}
}
var a = ['a', 'b', 'c', 'd', 'e'];
var list = new CustomArray(a)
console.log('list:', list);
console.log('remove:', list.remove('c'));
console.log('list:', list);
问题是当我打电话时。拼接() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice它从数组中删除元素,但也返回已删除元素的数组,实际上它返回我的子类 CustomArray 的新实例,该实例应该使用数组类型的参数启动,但 .splice() 使用整数类型的参数启动它。
这是我认为当我打电话时会发生的情况的示例。拼接() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice:
假设我们有实例list
of CustomArray
以争论开始的课程['a','b','c','d','e']
然后我们调用方法list.remove('c')
。 (就像代码片段中一样)。
Method remove
of CustomArray
类检查索引c
在数组中['a','b','c','d','e']
,即2
然后调用method this.splice(2,1)
这应该删除数组中索引 2 处的 1 个元素['a','b','c','d','e']
。方法splice
删除元素c
形成数组,但也返回类似的东西new CustomArray(1)
因为从数组中删除了一个元素,所以它尝试创建长度为 1 的数组,但失败了,因为类CustomArray
是期望数组。
我想阻止splice
方法从启动一个新实例CustomArray
类并返回普通数组(Array 对象的实例)。
jsbin链接。 https://jsbin.com/boqomuj/1/edit?js,console