TypeScript Array <t> .splice覆盖

时间:2017-01-11 22:21:36

标签: javascript typescript

在源自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

1 个答案:

答案 0 :(得分:1)

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

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);
    }
}

但我没有测试过这个。