从if else转换为switch语句 [英] convert from if else to switch statement
问题描述
我有以下if,否则if,else构造,我只是好奇我如何将构造转换为switch语句。
I have the following if, else if, else construct and I am just curious how I could convert such as construct into a switch statement.
var emailSubject = email.subject.toLowerCase();
if(emailSubject.indexOf("account request") >= 0){
//do acct req
}else if(emailSubject.indexOf("accounts pending removal for") >= 0){
//do account removal
}else if(emailSubject.indexOf("listserv application") >= 0){
//do listserv app
}else if(emailSubject.indexOf("student organization webmaster transfer request") >= 0){
//do webmaster xfer
}else{
//do default
}
我的想法是,但我不认为这是正确的:
My thoughts are but I do not think this is correct:
switch(emailSubject){
case this.indexOf("account request"):
//do acct request
break;
default:
//do default
}
或
switch(0){
case emailSubject.indexOf("accounts pending removal"):
//process account pending removal
break;
default:
//do default behavior
}
推荐答案
您的示例代码在大多数语言中都不能轻易转换为switch语句,也不应该。 switch
用于将单个变量与一系列常量值进行比较,而您的逻辑需要与非常量值进行比较,没有变量可与之进行比较。 如果
/ 否则,如果
是您案件的正确结构。
Your example code cannot easily be converted to a switch statement in most languages, nor should it. switch
is for comparing a single variable against a range of constant values, whereas your logic requires comparison against non-constant values, with no variable to compare them with. if
/else if
is the correct construction for your case.
这篇关于从if else转换为switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!