Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript的数组子类中使用.splice方法?_Javascript_Arrays_Subclass_Mutators - Fatal编程技术网

在javascript的数组子类中使用.splice方法?

在javascript的数组子类中使用.splice方法?,javascript,arrays,subclass,mutators,Javascript,Arrays,Subclass,Mutators,我试图创建javascript数组的一个子类。我想用数组类型参数初始化子类,并添加一个方法从数组(子类)中删除一个元素 我的代码如下所示: 类CustomArray扩展了数组{ 构造函数(数组){ console.log('启动数组:',数组) 超级(…阵列); } 移除(元素){ 设index=this.indexOf(元素); 如果(索引>-1){ 返回此。拼接(索引,1); } 返回[]; } } 变量a=['a','b','c','d','e']; 变量列表=新的自定义数组(a) l

我试图创建javascript数组的一个子类。我想用数组类型参数初始化子类,并添加一个方法从数组(子类)中删除一个元素

我的代码如下所示:

类CustomArray扩展了数组{
构造函数(数组){
console.log('启动数组:',数组)
超级(…阵列);
}
移除(元素){
设index=this.indexOf(元素);
如果(索引>-1){
返回此。拼接(索引,1);
} 
返回[];
}
}
变量a=['a','b','c','d','e'];
变量列表=新的自定义数组(a)
log('list:',list);
console.log('remove:',list.remove('c');
log('list:',list)
我想阻止
splice
方法启动
CostomArray
类的新实例,而是返回普通数组(一个
array
对象的实例)

然后,您需要使用不同的名称创建不同的方法。
splice
的语义是:;它们构成了
数组
类型的契约。让您的
CostomArray
违反该约定意味着它不再是
数组
,而是类似于数组的东西,不应该扩展
数组

由于您的方法被称为
remove
,这很好;如果希望
remove
返回
Array
,而不是
CostomArray
,您只需要自己实现逻辑:

remove(element) {
  let index = this.indexOf(element);
  if (index > -1) {
    const newLength = this.length - 1;
    while (index < newLength) {
        this[index] = this[index + 1];
        ++index;
    }
    this.length = newLength;
    return [element];
  } 
  return [];
}
删除(元素){
设index=this.indexOf(元素);
如果(索引>-1){
const newLength=this.length-1;
while(索引


当然,在各种
Array.prototype
方法调用时,也可以使
CostomArray
的构造函数正常工作。(您在问题中遇到的一个可以正常工作,除了用
console.log
记录您不期望的内容之外)

有可能让
splice
返回一个标准数组,这样就不用调用构造函数了。这是通过更改自定义类的类型来实现的,它决定了将使用哪个构造函数。但请注意,这不仅会影响
拼接
,还会影响所有其他创建新实例的方法,包括
映射
过滤器
切片

您可以通过覆盖相应的静态getter来更改
属性:

类CustomArray扩展了数组{
静态获取[Symbol.species](){return Array;}/-1){
返回this.splice(index,1);//现在调用数组构造函数,而不是CustomArray
} 
返回[];
}
}
变量a=['a','b','c','d','e'];
变量列表=新的自定义数组(a)
log('list:',list);
console.log('remove:',list.remove('c');
log('list:',list);
//对其他方法影响的一些示例
console.log(list.map(x=>x)instanceof CustomArray);//假的
console.log(list.filter(x=>1)instanceof CustomArray);//假的
console.log(list.slice()instanceof CustomArray);//假的
console.log(list.concat()instanceof CustomArray);//假的
//不返回新实例的其他方法不受影响:
console.log(list.reverse()instanceof CustomArray);//真的

console.log(list.sort()instanceof CustomArray);//是的
FWIW,我刚刚注意到我的答案中有一个我已经修复的代码错误(缺少
++index;
行)。
CustomArray
CostomArray
?感谢对
++index
的修复,但我使用了for loop而不是while。这是CustomArray,我在问题中编辑了它。。