[英]TypeScript Array<T>.splice override
在派生自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);
}
}
但我沒有測試過這個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.