重构 if else 语句

Refactoring if else statement

这是我的方法:

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 中添加更多键。