Javascript 如何将此代码转换为助手函数?
我正在尝试将这段有条件的代码转换成一个助手函数,通过使用switch语句而不是if语句,我可能会对其进行改进,从而最大限度地减少组件中当前的代码量。如何在新文件中执行此操作并将其导入组件Javascript 如何将此代码转换为助手函数?,javascript,reactjs,vue.js,helper,Javascript,Reactjs,Vue.js,Helper,我正在尝试将这段有条件的代码转换成一个助手函数,通过使用switch语句而不是if语句,我可能会对其进行改进,从而最大限度地减少组件中当前的代码量。如何在新文件中执行此操作并将其导入组件 import { USER_TYPES } from '../../constants/user'; const usertypeToName = { 1: 'client', 2: 'supportWorker', 3: 'accountManager', }; if (this.$route.par
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
作为数组,然后使用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
这就是你要找的吗
## util.js
import { USER_TYPES } from '../../constants/user';
const userTypeMap = {
client: USER_TYPES.client,
supportWorker: USER_TYPES.supportWorker,
accountManager: USER_TYPES.accountManager,
};
export function mapUserType(name) {
// Fallback to 0 incase mapping does not exist
return userTypeMap[name] || 0
}
## component.js
import { mapUserType } from './util.js'
const userType = mapUserType(this.$route.params.userType)
您只需执行
userToName[$route.params.userType]??0
无需手动检查那里的所有键。@该工具可能存在以下情况:userToName[$route.params.userType]
其他错误值,假设名为default
的键存在,但只想访问给定的键,否则返回0
,在这种情况下,上述方法将不起作用