这段 if...else 有优雅的写法吗?

查看 306|回复 22
作者:waiaan   
function onSortChange({ order, prop }) {
      let sortType = 0
      if (order === 'descending') {
        if (prop === 'thisYearIncome') {
          sortType = 1
        }
        if (prop === 'lastYearIncome') {
          sortType = 3
        }
        if (prop === 'rate') {
          sortType = 5
        }
      } else {
        if (prop === 'thisYearIncome') {
          sortType = 2
        }
        if (prop === 'lastYearIncome') {
          sortType = 4
        }
        if (prop === 'rate') {
          sortType = 6
        }
      }
      this.fetchData(sortType)
    }
谢谢。
Ericcccccccc   
我感觉最多搞个 map 套一下 prop 和 sortType
外层的 if else 逻辑清晰不用改吧。
ma836323493   
简单 枚举套枚举
ajaxgoldfish   
没事,无伤大雅,大道至简,要是再多的话,switch case 走一个
emeab   
```
function onSortChange({ order, prop }) {
const sortMapping = {
descending: {
thisYearIncome: 1,
lastYearIncome: 3,
rate: 5
},
ascending: {
thisYearIncome: 2,
lastYearIncome: 4,
rate: 6
}
};
// Get the sort type from the mapping based on the order and property
const sortType = sortMapping[order][prop] || 0; // Default to 0 if not found
this.fetchData(sortType);
}
```
pkokp8   
map? 不会 js ,大概这个意思
sortTypeMap[order][prop]=0-6
fetchData(sortTypeMap[order][prop])
pkokp8   
另外,第二层的第 2/3 个 if 少了 else ,会多两次判断,js 应该也支持 else if
tomatocici2333   
switch case 呗 = =看着不累
lingyi95   
你去问 gpt ,它可以给你优化成 10 行代码
mowen1992   
通义灵码来了:
function onSortChange({ order, prop }) {
// 使用映射对象来简化条件判断逻辑
const sortOrders = {
'thisYearIncome': { descending: 1, ascending: 2 },
'lastYearIncome': { descending: 3, ascending: 4 },
'rate': { descending: 5, ascending: 6 },
};
try {
// 检查 prop 是否存在于映射对象中
if (!sortOrders.hasOwnProperty(prop)) {
throw new Error(`Invalid property: ${prop}`);
}
// 检查 order 是否有效
if (!sortOrders[prop].hasOwnProperty(order)) {
throw new Error(`Invalid order: ${order}`);
}
// 直接通过映射对象获取 sortType
const sortType = sortOrders[prop][order];
// 调用 fetchData 方法更新数据
this.fetchData(sortType);
} catch (error) {
console.error('Error in onSortChange:', error.message);
// 可以在这里添加额外的错误处理,例如通知用户或记录日志
}
}
您需要登录后才可以回帖 登录 | 立即注册

返回顶部