【发布时间】:2021-01-30 06:14:41
【问题描述】:
我使用以下方法对可重复使用的 Material 数据表中的数据(数组)进行排序:
sortData(sortParameters: Sort) {
const keyName = sortParameters.active;
if (sortParameters.direction === 'asc') {
this.tableData = this.tableData.sort((a, b) => a[keyName].localeCompare(b[keyName]));
}
else if (sortParameters.direction === 'desc') {
this.tableData = this.tableData.sort((a, b) => b[keyName].localeCompare(a[keyName]));
}
else {
this.getStudents();
}
}
但是,虽然它适用于 name 字段,但它不适用于 id 字段。关于此方法的另一个问题是我想忽略 name 的空格并希望将 trim() 方法用于排序值。它正在工作,但我认为我必须找到另一种适用于 id 列的解决方案。有什么解决办法吗?
【问题讨论】:
-
id中值的类型是什么?它也是字符串还是其他什么?
-
@ChristianFritz 它们是整数,而不是字符串。 1,2,3 等值(顺序 id 值)。
-
关于排序 int 和 string 值的任何想法?
-
那么问题来了:JS 中的数字没有 localeCompare 函数。您需要实现一个排序函数,该函数将根据
typeof a[keyName]区分大小写,或者更好的是,为每个键设置单独的排序函数。
标签: javascript angularjs angular typescript ecmascript-6