创建一个函数而不是多个函数以按列排序
Make one function instead of many to sort by column
我想知道如何只使用一个函数来对数组的列进行排序。
目前我对每一列都有很多这样的功能:
sort() {
if (this.sortAsc == false) {
this.tab.sort((a, b) => {
return a.name.localeCompare(b.name);
});
this.sortAsc = true;
} else {
this.tab.sort((a, b) => {
}
return b.name.localeCompare(a.name);
});
this.sortAsc = false;
}
}
一块 table:
...
<tr>
<th (click)="sort()">Name</th>
...
</tr>
</thead>
<tbody>
<tr *ngFor="let item of tab" (click)="getById(item.id)" tabindex="0">
<td> {{ item.name }} </td>
...
</tr>
...
您可以添加一个参数来排序,例如您要排序的变量名称:sort('name')
在排序函数中,您可以使用该参数来区分您想要排序的内容。
sort(val: string) {
if(!this.sortAsc) {
this.tab.sort((a,b) => {
return a[val].localeCompare(b[val]);
});
this.sortAsc = true;
}
...
}
我想知道如何只使用一个函数来对数组的列进行排序。 目前我对每一列都有很多这样的功能:
sort() {
if (this.sortAsc == false) {
this.tab.sort((a, b) => {
return a.name.localeCompare(b.name);
});
this.sortAsc = true;
} else {
this.tab.sort((a, b) => {
}
return b.name.localeCompare(a.name);
});
this.sortAsc = false;
}
}
一块 table:
...
<tr>
<th (click)="sort()">Name</th>
...
</tr>
</thead>
<tbody>
<tr *ngFor="let item of tab" (click)="getById(item.id)" tabindex="0">
<td> {{ item.name }} </td>
...
</tr>
...
您可以添加一个参数来排序,例如您要排序的变量名称:sort('name') 在排序函数中,您可以使用该参数来区分您想要排序的内容。
sort(val: string) {
if(!this.sortAsc) {
this.tab.sort((a,b) => {
return a[val].localeCompare(b[val]);
});
this.sortAsc = true;
}
...
}