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

35 天前
 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)
    }

谢谢。

6328 次点击
所在节点    JavaScript
76 条回复
Ericcccccccc
35 天前
我感觉最多搞个 map 套一下 prop 和 sortType

外层的 if else 逻辑清晰不用改吧。
ma836323493
35 天前
简单 枚举套枚举
ajaxgoldfish
35 天前
没事,无伤大雅,大道至简,要是再多的话,switch case 走一个
2kCS5c0b0ITXE5k2
35 天前
```
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
35 天前
map? 不会 js ,大概这个意思
sortTypeMap[order][prop]=0-6
fetchData(sortTypeMap[order][prop])
pkokp8
35 天前
另外,第二层的第 2/3 个 if 少了 else ,会多两次判断,js 应该也支持 else if
tomatocici2333
35 天前
switch case 呗 = =看着不累
lingyi95
35 天前
你去问 gpt ,它可以给你优化成 10 行代码
mowen1992
35 天前
通义灵码来了:
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);
// 可以在这里添加额外的错误处理,例如通知用户或记录日志
}
}
Kakaaa
35 天前
xiangyuecn
35 天前
var order="xxx",prop="rate"
var sortType=(
/**/ ({descending:
/*----*/ {thisYearIncome:1,lastYearIncome:3,rate:5}
/**/ })[order] ||
/*----*/ {thisYearIncome:2,lastYearIncome:4,rate:6}
)[prop]||0;
davin
35 天前
先定义枚举吧,不然时间久了怎么解释这些 1 到 6
···
enum SortType {
THIS_YEAR_INCOME_DESC = 1,
THIS_YEAR_INCOME_ASC = 2,
LAST_YEAR_INCOME_DESC = 3,
LAST_YEAR_INCOME_ASC = 4,
RATE_DESC = 5,
RATE_ASC = 6
}
···
yangg
35 天前
接口设计有问题,搞什么 1 ,2,3 ,4,5,6 的参数
bertonzh
35 天前
{
'descending-thisYearIncome': 1,
'descending-lastYearIncome': 3,
}[`${order}-${prop}`]
MorJS
35 天前
function onSortChange({ order, prop }) {
const sortMap = {
'descending': { 'thisYearIncome': 1, 'lastYearIncome': 3, 'rate': 5 },
'ascending': { 'thisYearIncome': 2, 'lastYearIncome': 4, 'rate': 6 }
};

const sortType = sortMap[order]?.[prop] || 0;

this.fetchData(sortType);
}
yuzo555
35 天前
function onSortChange({ order, prop }) {
const sortTypes = {
thisYearIncome: order === 'descending' ? 1 : 2,
lastYearIncome: order === 'descending' ? 3 : 4,
rate: order === 'descending' ? 5 : 6,
};
this.fetchData(sortTypes[prop] || 0);
}
foolnius
35 天前
const defineObject = {
descending_thisYearIncome: 1, //注释
thisYearIncome: 3, //注释
descending_lastYearIncome: 3, //注释
lastYearIncome: 4, //注释
descending_rate: 5, //注释
rate: 6, //注释
};

function onSortChange({ order, prop }) {
const key = `${order === "descending" ? `${order}_` : ""}${prop}`;
this.fetchData(defineObject[key] ?? 0);
}
NessajCN
35 天前
function onSortChange({ order, prop }) {
const l=["thisYearIncome", "lastYearIncome", "rate"];
const sortType = order === "descending" ? l.indexOf(prop)*2+1 : l.indexOf(prop)*2+2;
this.fetchData(sortType)
}
wysnxzm
35 天前
switch 或者 map
各种设计模式最终也都是依赖 map 进行实现比如策略模式
z1829909
35 天前
举手提问, 这里为啥需要转成数字传入 fetchData, 为什么不在这一层直接转为查询条件传入 fetchData.
因为我觉得 sortType 在 fetchData 中又要被拆开解析, 看代码的人又要去记 sortType 的意思, 多一层开销

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1037129

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX