javascript - TypeScript - 数组排序扩展方法

标签 javascript arrays typescript

我正在寻找在 TypeScript 中创建一个数组扩展“排序”方法,其中数组可以由各种对象类型组成。我可以从任何组件调用这个扩展方法。

这种排序需要接受一个对象属性来排序(当然,该属性可以是数字或字符串)和枚举类型的方向(升序 1 或降序 -1)。我有数组,我有 sortDirection 的枚举。但是我在哪里/如何构建排序方法来像这样调用它?

myArrayOfObjects.sort('name', sortDirection.Descending);

这是我现有的组件级排序,我正在尝试将其转换为可以从任何地方调用的扩展方法。将方向转换为枚举并传递它很容易,但我真的试图将其作为扩展方法:

 sort(property: string): void {
    this.isDescending = !this.isDescending;
    this.column = property;
    const direction = this.isDescending ? 1 : -1;

    this.searchResults.sort(function (a, b) {
        if (a[property] < b[property]) {
            return -1 * direction;
        } else if (a[property] > b[property]) {
            return 1 * direction;
        } else {
            return 0;
        }
    });
    this.currentPage = 0;
}

this.searchResults 如下,但它可以是任何数组或任何具有属性的对象。同样,这目前是一个组件级函数,我想将其转换为数组的扩展方法:

@Input() searchResults: IPersonSummary[];

最佳答案

因为 TypeScript 已加载定义了具有名称排序的方法的基本类型,所以您无法使用相同的名称重新定义它。如果您考虑使用一些不同的名称(例如我选择 mySort),您可以这样做。您需要在 Array 接口(interface)中定义它并将您的函数分配给 Array 原型(prototype)。 使用新名称定义扩展是最佳实践,因为自从覆盖某些基本方法后,您就无法随时调用基本方法。如果您考虑将来某个时候调用基本方法,您将会遇到大麻烦。

推荐的方法:

interface Array<T> {
    mySort(property: string): void;
}

Array.prototype.mySort = function (property: string): void {
    this.isDescending = !this.isDescending;
    this.column = property;
    const direction = this.isDescending ? 1 : -1;

    this.searchResults.sort(function (a, b) {
        if (a[property] < b[property]) {
            return -1 * direction;
        } else if (a[property] > b[property]) {
            return 1 * direction;
        } else {
            return 0;
        }
    });
    this.currentPage = 0;
}

关于javascript - TypeScript - 数组排序扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44982139/

相关文章:

typescript - 消除 TypeScript 中的类型歧义

javascript - 在 Ionic 2 应用程序中显示 Youtube

javascript - 在其他选项卡上的一个 Web 浏览器实例中登录到应用程序

javascript - 在浏览器 HTML 元素上触发左键单击事件 - 直接从键盘

javascript Date.parse 假设 2 月和所有月份有 31 天?

javascript - 从 MongoDB 中的另一个集合中添加值

javascript - Mongodb:一次更新同一文档中多个数组的元素

typescript - ionic 2,仅在事件页面上运行脚本

arrays - Swift - 将数据加载到结构数组中

java - java中二维数组的顺序打乱