Javascript 重构if-else语句
这是我的方法:Javascript 重构if-else语句,javascript,vue.js,vuex,Javascript,Vue.js,Vuex,这是我的方法: Object.entries(query).forEach(([key, value]) => { if (key === 'team_ids') { if (typeof value === 'string') { this.items.push(this.$store.getters.teamById(value)); } else { value.forEach((itemId) => { this.i
Object.entries(query).forEach(([key, value]) => {
if (key === 'team_ids') {
if (typeof value === 'string') {
this.items.push(this.$store.getters.teamById(value));
} else {
value.forEach((itemId) => {
this.items.push(this.$store.getters.teamById(itemId));
});
}
else if (key === 'close_ids') {
if (typeof value === 'string') {
this.items.push(this.$store.getters.closeFriendsById(value));
} else {
value.forEach((friendId) => {
this.items.push(this.$store.getters.closeFriendsById(friendId));
});
}
} else {
if (key === 'name') this.name = value;
if (key === 'patr') this.patr= value;
}
});
我正试图重构它,但现在我被难住了…看起来不太好。
有什么建议吗?不错,有三元运算符可以使代码更干净,if语句也缩短了。但是,如果要重构它,您应该提供一些关于逻辑的信息,因为它在重构中很重要。您可以使用switch语句重构if语句 试试这个:
Object.entries(query).forEach(([key, value]) => {
switch(key) {
case 'name' :
this.name = value; break;
case 'patr' :
this.patr = value; break;
default:
let getterMap = {
'team_ids': 'teamById',
'close_ids': 'closeFriendsById'
}
if(Array.isArray(value)) {
value.forEach((itemId) => {
this.items.push(this.$store.getters[getterMap[key]](itemId));
});
} else {
this.items.push(this.$store.getters[getterMap[key]](value));
}
break;
}
});
如果愿意,您可以在getterMap中添加更多键。您想重构什么,为什么?