在扩展数组上调用splice会导致错误,我不知道为什么



当我在类中调用Remove时,当涉及到this.splice时,它会抛出一个错误。请注意,this.index运行良好。你知道为什么吗?你有变通办法吗?

export class DefaultReorderableList<T> extends Array<T> implements ReorderableList<T> {
constructor(items: Array<T>=[]) {
super(...items);
Object.setPrototypeOf(this, new.target.prototype);
}

Remove(item: T | ((element:T)=>boolean) ): void {
let index: number = -1;
if(item instanceof ((element: T)=> Boolean)){
for(let i:number = 0, l:number = this.length; i<l; i++){
let foo:(element:T)=>boolean =item as (element:T)=>boolean;
if(foo(this[i])){
index=i;
}
}
}
index = this.indexOf(item as T);
if (index >= 0) {
this.splice(index,1);
}
}
SwapToPrevious(index: number): void {
if(index == 0){
return;
}
if(index < 0 || index >= this.length){
throw new Error("Out of Range");
}
let indexedValue = this[index];
this[index] = this[index -1];
this[index-1]= indexedValue;
}

SwapToNext(index: number): void {
if(index == 0){
return;
}
if(index < 0 || index >= this.length){
throw new Error("Out of Range");
}
let indexedValue = this[index];
this[index] = this[index + 1];
this[index + 1]= indexedValue;
}
}

现在,您可以在JavaScript中运行它:https://jsfiddle.net/La3pqj1v/

class DefaultReorderableList extends Array{
constructor(items =[]) {
super(...items);
Object.setPrototypeOf(this, new.target.prototype);
}

Remove(item) {
let index = -1;
index = this.indexOf(item); // works
if (index >= 0) {
this.splice(index,1); // does not work
}
}
SwapToPrevious(index) {
if(index == 0){
return;
}
if(index < 0 || index >= this.length){
throw new Error("Out of Range");
}
let indexedValue = this[index];
this[index] = this[index -1];
this[index-1]= indexedValue;
}

SwapToNext(index) {
if(index == 0){
return;
}
if(index < 0 || index >= this.length){
throw new Error("Out of Range");
}
let indexedValue = this[index];
this[index] = this[index + 1];
this[index + 1]= indexedValue;
}
}
let testClass = new DefaultReorderableList();
testClass.push("a");
testClass.push("b");
console.log(testClass[0])
testClass.SwapToPrevious(1); // works
console.log(testClass[0])
testClass.Remove("b"); // does not work

问题是splice返回一个包含已删除项的数组。此数组与方法接收器(this值(属于相同的种类(读作:subclass(,即在您的情况下为DefaultReorderableListsplice实例化了一个长度为的new DefaultReorderableList(1),因为任何Array构造函数都应该支持它。您的构造函数违反了实现该接口的约定,并在尝试迭代super(...items)中的数字时导致异常。

请参见未定义扩展阵列映射时。

通过完全删除构造函数(或重新实现默认的constructor(...items) { super(...items); }(来修复它。如果要创建一个实例并传递一个数组对其进行初始化,请使用DefaultReorderableList.from([…])

最新更新