javascript - TypeScript Array<T>.splice 覆盖

标签 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

最佳答案

发生这种情况的原因似乎是 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);
    }
}

但我还没有测试过这个。

关于javascript - TypeScript Array<T>.splice 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601793/

相关文章:

javascript - 如何从 Vue Pinia 商店中的操作导航到另一条路线?

javascript - React useCallback 设置对回调内调用的函数的依赖

javascript - 将对象数组添加到一起

c# - 在页面加载时禁用下拉列表

javascript - 将 svg 转换为 png 时添加 css 样式

javascript - 添加带有引用字段的 Parsley.js 验证器

javascript - 构建nodeJs时 typescript 错误

typescript - 无法为字符串枚举创建用户定义的类型保护

c# - 通用类型代码中的类型参数是否有命名约定(bracy flavoured)

javascript - jquery 当前导航项选择器