在派生自 Array<T>
的类中,我有一个splice
覆盖:
public splice(start?: number, deleteCount?: number, ...items: T[]): T[] {
return super.splice(start, deleteCount, ...items);
}
编译为...
SuperArray.prototype.splice = function (start, deleteCount) {
var items = [];
for (var _i = 2; _i < arguments.length; _i++) {
items[_i - 2] = arguments[_i];
}
return _super.prototype.splice.apply(this, [start, deleteCount].concat(items));
};
这根本不起作用。它完全破坏了拼接!它编译这个的方式有问题吗.apply(this, [start, deleteCount].concat(items))
以及如何修复它?
拼接发生了什么?为什么坏了?
array.splice(0); // array unaffected
最佳答案
发生这种情况的原因似乎是 deleteCount
是 undefined
,如果您尝试这样做:
let a = [1, 2, 3];
a.splice(0, undefined); // []
console.log(a); /// [1, 2, 3]
完全一样的事情。
为了解决这个问题,您需要自己构建参数数组,如下所示:
class MyArray<T> extends Array<T> {
public splice(start?: number, deleteCount?: number, ...items: T[]): T[] {
if (start == undefined) {
start = 0; // not sure here, but you wanted it to be optional
}
if (deleteCount == undefined) {
deleteCount = this.length - start; // the default
}
const args = ([start, deleteCount] as any[]).concat(items);
return super.splice.apply(this, args);
}
}
或者类似的东西:
public splice(start?: number, deleteCount?: number, ...items: T[]): T[] {
if (deleteCount != undefined) {
return super.splice(start, deleteCount, ...items);
} else {
return super.splice(start, ...items);
}
}
但我还没有测试过这个。
关于javascript - TypeScript Array<T>.splice 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601793/