优化 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] curr_data.children.sort((a, b) => { if (is_desc) { return a.suffix < b.suffix ? 1 : -1 } return a.suffix curr_data.children.sort((a, b) => { if (is_desc) { return a.bytes < b.bytes ? 1 : -1 } return a.bytes 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; } // 如果两个属性值相等,则返回 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 方法来处理所有排序任务。该方法接受三个参数:
curr_data:要排序的对象数组prop:要基于的属性名进行排序is_desc:是否为降序排序(布尔值)
以上就是如何优化 JavaScript 代码,以便使用更简洁的方式对对象数组进行排序?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2651213.html