【发布时间】:2020-11-04 20:39:03
【问题描述】:
当我在课堂上调用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
【问题讨论】:
-
错误说明了什么?
-
@imvain2 取决于运行时
-
@Bergi 现在我有时间添加一个可运行的示例
-
顺便说一句,
Object.setPrototypeOf(this, new.target.prototype);在任何 ES6 兼容的环境中都应该是不必要的
标签: javascript typescript