javascript - 如何将此代码转换为辅助函数?
问题描述
我正在尝试将这段可能通过使用 switch 语句而不是 if 语句来改进的条件代码转换为辅助函数,以最小化我当前在组件中拥有的代码量。如何在新文件中执行此操作并将其导入到我的组件中?
import { USER_TYPES } from '../../constants/user';
const usertypeToName = {
1: 'client',
2: 'supportWorker',
3: 'accountManager',
};
if (this.$route.params.userType === usertypeToName[1]) {
return USER_TYPES.client;
}
if (this.$route.params.userType === usertypeToName[2]) {
return USER_TYPES.supportWorker;
}
if (this.$route.params.userType === usertypeToName[3]) {
return USER_TYPES.accountManager;
}
return 0;
解决方案
您应该简单地拥有usertypeToName
as 数组,然后使用find
import { USER_TYPES } from '../../constants/user';
const usertypeToName = ['client', 'supportWorker','accountManager']
// find key
const key = usertypeToName.find(v=> v === this.$route.params.userType)
// use dynamic property accessor
return key ? USER_TYPES[key] : 0
推荐阅读
- sql-server - 使用代码从 VB NET 中的 DevExpress 将数据从 SQLServer 添加到 XRLabels
- excel - 在 Selenium VBA 中提取变化的 XPath
- python - Octave int 太大
- regex - perl 正则表达式不匹配并包含下一行
- amazon-web-services - 我可以将外部网络适配器连接到 Window Server 吗?
- rust - 如何告诉借用检查器清除的 Vec 不包含借用?
- python - 并发用户的 Python API 性能问题
- php - 接口和解释语言
- async-await - Blazor 页面组合框数据源到异步方法
- google-workspace - 使用 App 脚本向自定义属性添加值