【问题标题】:Why sorting is not working on some of the columns?为什么排序不适用于某些列?
【发布时间】:2021-01-13 19:20:24
【问题描述】:

我在表格上使用了列排序。它在名字和姓氏列上工作正常,但在 dl 和 dl 分数上它不起作用。你能看看它并帮我解决它。

您可以在这里查看:https://stackblitz.com/edit/angular-ivy-87hi8i?file=src%2Fapp%2Fapp.component.html

sort(property: any) {
    this.isDesc = !this.isDesc;
    this.column = property;
    let direction = this.isDesc ? 1 : -1;
    this.allUser.sort(function(
      a: { [x: string]: number },
      b: { [x: string]: number }
    ) {
      if (a[property] < b[property]) {
        return -1 * direction;
      } else if (a[property] > b[property]) {
        return 1 * direction;
      } else {
        return 0;
      }
    });
  }

标记

<tr>
<th *ngIf="!isEdit">Edit</th>
<th [ngClass]="{pointer: true, active:column=='first_name',desc:isDesc, asc:!isDesc}"
(click)="sort('first_name')">First Name</th>
<th [ngClass]="{pointer: true, active:column=='last_name',desc:isDesc, asc:!isDesc}"
(click)="sort('last_name')">Last Name</th>
<th>Email</th>
<th>Gender</th>
<th>DOB</th>
<th>Impact</th>
<th>Score</th>
<th [ngClass]="{pointer: true, active:column=='dl',desc:isDesc, asc:!isDesc}" (click)="sort('dl')">
DL</th>
<th [ngClass]="{pointer: true, active:column=='co_score',desc:isDesc, asc:!isDesc}"
(click)="sort('co_score')">DL Score</th>
<th></th>
</tr>

【问题讨论】:

    标签: javascript angular typescript sorting


    【解决方案1】:

    你声明你的排序方法:

     this.allUser.sort(function(
          a: { [x: string]: number },
          b: { [x: string]: number }
        )
    

    您是说数组中的所有对象都有返回数字的键。

    因此,当您对 first_name 属性进行排序时,它会在执行 a['first_name'] 时找到类似 A Male 的值,这根本不是一个数字,所以很明显这是一个逻辑问题。无论如何,排序在运行时都适用,因为 javascript 可以像这样对字符串进行排序。

    但是当您对dl 进行排序时,该属性甚至不存在于您的对象中,因此它会将undefinedundefined (a['dl']) 进行比较,它们相等,因此不会发生排序。

    因此,如果您想对其进行排序,请确保使用属性 dl 的值填充您的对象。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多