【问题标题】:Refactoring if else statement重构 if else 语句
【发布时间】:2021-04-11 14:20:25
【问题描述】:

这是我的方法:

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;  
  }
});

我正在尝试重构它,但现在我被难住了......
它看起来不太好。 有什么建议吗?

【问题讨论】:

  • 你想重构什么,为什么?

标签: javascript vue.js vuex


【解决方案1】:

您可以使用 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 中添加更多键。

【讨论】:

    【解决方案2】:

    还不错,您有三元运算符,可以使代码更清晰,并且缩短了 if 语句。但是,如果你想重构它,你应该提供一些关于逻辑的信息,因为它在重构中很重要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 2015-07-06
      相关资源
      最近更新 更多