最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

if statement - Optimize if condition javascript - Stack Overflow

programmeradmin4浏览0评论

I am just a newbie in javascript, this is how i am writing if condition in a javascript,

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

Is there a better way to do it?

I am just a newbie in javascript, this is how i am writing if condition in a javascript,

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

Is there a better way to do it?

Share Improve this question edited Oct 21, 2015 at 5:49 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Oct 21, 2015 at 5:45 user3721335user3721335 514 bronze badges 1
  • The ma after function is not required – Tushar Commented Oct 21, 2015 at 5:50
Add a ment  | 

4 Answers 4

Reset to default 6

You can use an object as a map:

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

  return map[accType];
}

Or as @Tushar pointed out:

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

Assuming accType will always be passed to function.

  1. Convert the string to first capital and other small case
  2. Append Customer to it

Code:

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

Code Explanation:

  1. accType[0]: Get the first character of the string
  2. accType.slice(1).toLowerCase(): Get the string except first character

Try using the switch block if you are paring the same variable against different values and having different things happen in different cases:

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

评论列表(0)

  1. 暂无评论