我只是一个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
总是传递给函数
- 将字符串转换为首大写和其他小写
- 将客户附加到
return accType[0] + accType.slice(1).toLowerCase() + ' Customer';
代码说明:
-
accType[0]
:获取字符串 的第一个字符 -
accType.slice(1).toLowerCase()
:获取除第一个字符 之外的字符串
如果您将相同的变量与不同的值进行比较,并在不同的情况下发生不同的事情,请尝试使用switch
块:
function setAccType(accType){
switch(accType) {
case "PLATINUM" :
return "Platinum Customer";
case "GOLD":
return "Gold Customer";
case "SILVER":
return "Silver Customer";
}
}