javascript - 单击表格标题对数组进行排序
问题描述
我想在单击表格标题时自动以两种方式(升序和降序)对数组进行排序
这是我正在使用的代码
SortLast() {
this.students.sort(function (a, b) {
var textA = a.lastName.toUpperCase();
var textB = b.lastName.toUpperCase();
if (textA < textB)
return -1
else if (textA > textB)
return 1
else
return 0;
});
}
所以我不想指定排序顺序,它会自动以一种方式排序,上面的数组学生被修补到 HTML 上的网格。
解决方案
存储排序状态,然后根据最后的排序按升序或降序排序。
ASC = "asc"
DESC = "desc"
class Table {
constructor(){
this.sortDir = null;
this.students = [{lastName: "John"}, {lastName: "Zoe"}, {lastName: "Ana"}];
}
isAsc(){ return this.sortDir === ASC; }
isDesc(){ return this.sortDir === DESC; }
sort() {
const scope = this;
this.sortDir = this.isAsc() ? DESC: ASC
this.students.sort(function (a, b) {
const textA = scope.isDesc() ? b.lastName.toUpperCase() : a.lastName.toUpperCase();
const textB = scope.isDesc() ? a.lastName.toUpperCase() : b.lastName.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0
});
}
}
尝试:
const table = new Table()
console.log(table.sortDir,table.students)
table.sort()
console.log(table.sortDir, table.students)
table.sort()
console.log(table.sortDir, table.students)
输出:
null [ { lastName: 'John' }, { lastName: 'Zoe' }, { lastName: 'Ana' } ]
asc [ { lastName: 'Ana' }, { lastName: 'John' }, { lastName: 'Zoe' } ]
desc [ { lastName: 'Zoe' }, { lastName: 'John' }, { lastName: 'Ana' } ]
推荐阅读
- croppie - Croppie:如何以 JPEG 而不是默认的 PNG 格式获取输出图像?
- amazon-dynamodb - DynamoDB putItem 并更新单个字段
- python - 如何扩展一个类是Python
- python - 为什么python只打印字典中的最后一个键?
- python - 为具有比较的函数创建网格网格
- python - 对熊猫数据框的所有列执行单变量回归,即按列单变量回归
- entity-framework - 在 linq Entity Framework Core 中使用 Join
- python - 正则表达式无法排除带有换行符的匹配项
- python - 对动态范围内的列求和
- javascript - 用javascript处理表单提交时formdata事件的目的是什么?