优化条件javascript



我只是一个javascript新手,这就是我如何在javascript中编写if条件,

function setAccType(accType) {
    if (accType == "PLATINUM") {
        return "Platinum Customer";
    } else if (accType == "GOLD") {
        return "Gold Customer";
    } else if (accType == "SILVER") {
        return "Silver Customer";
    }
},

有更好的方法吗?

可以使用对象作为映射:

function setAccType(accType){
  var map = {
    PLATINUM: 'Platinum Customer',
    GOLD: 'Gold Customer',
    SILVER: 'Silver Customer'
  }
  return map[accType];
}

或者正如@Tushar指出的:

var accountTypeMap = {
  PLATINUM: 'Platinum Customer',
  GOLD: 'Gold Customer',
  SILVER: 'Silver Customer'
}
function setAccType(accType){  
  return accountTypeMap[accType];
}

var TYPES = {
  "PLATINUM":"Platinum Customer",
  "GOLD":"Gold Customer",
  "SILVER":"Silver Customer"
}
function getType(acctType){
    return TYPES[acctType];
}

假设accType总是传递给函数

  1. 将字符串转换为首大写和其他小写
  2. 客户附加到
代码:

return accType[0] + accType.slice(1).toLowerCase() + ' Customer';

代码说明:

  1. accType[0]:获取字符串
  2. 的第一个字符
  3. accType.slice(1).toLowerCase():获取除第一个字符
  4. 之外的字符串

如果您将相同的变量与不同的值进行比较,并在不同的情况下发生不同的事情,请尝试使用switch块:

function setAccType(accType){
    switch(accType) {
        case "PLATINUM" :
            return "Platinum Customer";
        case "GOLD":
            return "Gold Customer";
        case "SILVER":
            return "Silver Customer";
     }
 }

最新更新