簡體   English   中英

重構 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 中添加更多鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM