在从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

最佳答案

似乎发生这种情况的原因是deleteCountundefined,如果您尝试这样做:

let a = [1, 2, 3];
a.splice(0, undefined); // []
console.log(a); /// [1, 2, 3]


完全一样。
为了克服这个问题,您需要自己构建arguments数组,如下所示:

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/

10-11 14:46