减少多个if函数到一个

时间:2020-07-23 12:14:56

标签: javascript google-apps-script google-sheets

我对下面的宏执行以下操作。如果搜索到的值['ASUS','LENOVO','DELL']是其中之一,则会写入['Computer']。如果想要的值['U.S.A','United Kingdom','Russia']是其中之一,则它将写为['Country']。我不想有两个if函数。我想要一个if函数。我怎样才能做到这一点?从现在开始谢谢你。

  batch_states, batch_next_states, batch_actions, batch_rewards, batch_dones = replay_buffer.sample(batch_size)
  
  print('log ',type(batch_states))
  print(batch_states)
  state = torch.from_numpy(batch_states)
  next_state = torch.from_numpy(batch_next_states)
  action = torch.from_numpy(batch_actions)
  reward = torch.from_numpy(batch_rewards)
  done = torch.from_numpy(batch_dones)

2 个答案:

答案 0 :(得分:2)

这就是我在GAS中处理此问题的方式:

  var comp = [['ASUS' , 'LENOVO', 'DELL'] ,     ['Computer']];
  var cont = [['U.S.A' , 'United Kingdom', 'Russia'] ,     ['Country']];
  var city = [['City1' , 'City2', 'City3'] ,     ['City']];      

  var findvalue = 'Russia';
  
  arr=[comp[0].indexOf(findvalue),cont[0].indexOf(findvalue),city[0].indexOf(findvalue)];
  
  if (arr[0] >=0){
         Logger.log(comp[1][0])
         }
  else if (arr[1] >=0){
  Logger.log(cont[1][0])
  }
  else if (arr[2] >=0){
  Logger.log(city[1][0])
  } 
  else {Logger.log("The item can not be found")}

答案 1 :(得分:2)

更简洁的答案:

var categories = [comp, cont, city];

for (var i in categories) {
    if (categories[i][0].indexOf(findvalue) > -1) {
        return categories[i][1];
    }
}
return 'not found';

如果以后添加类别,则更容易更新。