原代码
const next = () => {
switch (steps[current.value].type) {
case 'verifyPhoneNumber':
registerComp.value.registerFn();
break;
case 'accountInformation':
console.log(111);
break;
case 'selectServicePackage':
console.log(222);
break;
case 'registerFinish':
console.log(333);
break;
}
current.value++;
};
优化后:
将 switch
语句转换为对象字面量后,可以避免多次判断,从而提高代码的执行效率,
将对象缓存起来,可以避免每次调用 next
函数时都重新创建对象,也可以提高代码的执行效率
const actions = {
verifyPhoneNumber: () => {
registerComp.value.registerFn();
},
accountInformation: () => {
console.log(111);
},
selectServicePackage: () => {
console.log(222);
},
registerFinish: () => {
console.log(333);
},
};
const next = () => {
const type = steps[current.value].type;
if (actions[type]) {
actions[type]();
}
current.value++;
};