Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 重构if-else语句_Javascript_Vue.js_Vuex - Fatal编程技术网

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

您想重构什么,为什么?