
优化 javascript 排序代码
问题:
如何优化以下 javascript 代码,以便使用更简洁的方式对对象数组进行排序?
const sort_fun = {
名称: (curr_data, is_desc) =>
curr_data.children.sort((a, b) => {
if (is_desc) {
return a.pinyin[0] < b.pinyin[0] ? 1 : -1
}
return a.pinyin[0] < b.pinyin[0] ? -1 : 1
}),
类型: (curr_data, is_desc) =>
curr_data.children.sort((a, b) => {
if (is_desc) {
return a.suffix < b.suffix ? 1 : -1
}
return a.suffix < b.suffix ? -1 : 1
}),
大小: (curr_data, is_desc) =>
curr_data.children.sort((a, b) => {
if (is_desc) {
return a.bytes < b.bytes ? 1 : -1
}
return a.bytes < b.bytes ? -1 : 1
}),
时间: (curr_data, is_desc) =>
curr_data.children.sort((a, b) => {
if (is_desc) {
return a.timestamp.mtime < b.timestamp.mtime ? 1 : -1
}
return a.timestamp.mtime < b.timestamp.mtime ? -1 : 1
}),
}回答:
立即学习“Java免费学习笔记(深入)”;
我们可以使用以下方法优化代码:
const sortFun = {
// 通用排序方法
sortData: function(curr_data, prop, is_desc) {
// 根据 is_desc 的值确定排序的方向
const direction = is_desc ? 1 : -1;
// 使用 sort 方法对 curr_data.children 数组进行排序
// 注意这里使用了箭头函数
return curr_data.children.sort((a, b) => {
// 通过 prop 参数指定的属性名获取 a 和 b 的属性值
// 如果属性是嵌套的,例如 'timestamp.mtime',这里会递归地访问到这个深层属性
const aValue = prop.split('.').reduce((o, i) => o[i], a);
const bValue = prop.split('.').reduce((o, i) => o[i], b);
// 比较两个属性值
if (aValue < bValue) {
// 如果 a 的属性值小于 b 的属性值,则返回负数(升序)或正数(降序),根据 direction 的值
return direction * -1;
}
if (aValue > bValue) {
// 如果 a 的属性值大于 b 的属性值,则返回正数(升序)或负数(降序),根据 direction 的值
return direction * 1;
}
// 如果两个属性值相等,则返回 0,表示它们在排序中视为相等
return 0;
});
},
};
// 使用示例:
// 调用 sortData 方法进行排序
// 第一个参数是当前要排序的数据
// 第二个参数是要基于哪个属性进行排序
// 第三个参数是是否为降序排序
sortFun.sortData(curr_data, 'pinyin', false); // 升序排序 pinyin 属性
sortFun.sortData(curr_data, 'suffix', true); // 降序排序 suffix 属性
sortFun.sortData(curr_data, 'bytes', false); // 升序排序 bytes 属性
sortFun.sortData(curr_data, 'timestamp.mtime', true); // 降序排序 timestamp.mtime 属性在优化后的版本中,我们使用了一个通用的 sortdata 方法来处理所有排序任务。该方法接受三个参数:
以上就是如何优化 JavaScript 代码,以便使用更简洁的方式对对象数组进行排序?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号