javascript switch() 或 if()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5711347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript switch() or if()
提问by ianace
which would be better if i do this:
如果我这样做会更好:
if(message == 'redirect')
{
is_valid.accepted = true;
}
else if(message == 'invalid id')
{
is_valid.accepted = false;
}
else
{
is_valid.accepted = false;
}
or i do it this way
或者我这样做
switch (message)
{
case 'invalid id':
default:
is_valid.accepted = false;
break;
case 'redirect':
is_valid.accepted = true;
break;
}
回答by ninjagecko
You might use switch
if you foresaw needing to add lots of new cases.
switch
如果您预见需要添加大量新案例,您可能会使用它。
If you won't be adding many new cases, I might do, for clarity:
如果您不会添加许多新案例,为了清楚起见,我可能会这样做:
is_valid.accepted = message=='redirect';
(also note that your check for 'invalid id' does nothing)
(另请注意,您对“无效 ID”的检查没有任何作用)
Nevertheless if you had to add new things, notice how it's good you don't have to repeat yourself don't have to repeat yourself don't have to repeat yourself, also the sexy formatting:
尽管如此,如果您必须添加新内容,请注意不必重复自己不必重复自己不必重复自己,还有性感的格式:
switch (message)
{
case 'invalid id':
case 'penguin invasion':
case 'the internet is down':
case 'error not enough caffeine':
is_valid.accepted = false;
break;
case 'redirect':
case 'upvote me':
case 'vip':
case 'flamewar':
is_valid.accepted = true;
break;
default:
is_valid.accepted = false;
// perhaps log or something
}
Imagine all those ugly else and else-ifs you'd have otherwise.
想象一下所有那些丑陋的 else 和 else-ifs,否则你会拥有的。
sidenote: If you had really complicated rules, but still a whitelist-blacklist-on-a-single-flag paradigm, then:
旁注:如果你有非常复杂的规则,但仍然是一个白名单黑名单单标志范式,那么:
var blacklist = ['invalid id', 'penguin invasion', 'the internet is down' 'error not enough caffeine'];
var whitelist = ['redirect', 'upvote me', 'vip', 'flamewar'];
is_valid.accepted = whitelist.indexOf(message)!=-1;
You might also do this if you wanted to dynamically construct your whitelist.
如果您想动态构建白名单,也可以这样做。
回答by james2doyle
It depends on your definition of better. Do you want it to be a better reading experience or better performance?
这取决于你对更好的定义。你想要更好的阅读体验还是更好的性能?
I always jsPerf things. I don't really care much about readability if it makes my code faster/proper.
我总是jsPerf的东西。如果可读性能让我的代码更快/正确,我就不太关心可读性。
Here is a jsPerf of a bunch of different switch vs. if/else if/if ==/if === statements.
这是一堆不同 switch 与 if/else if/if ==/if === 语句的 jsPerf。
http://jsperf.com/switch-if-else/16
http://jsperf.com/switch-if-else/16
This is revision 16 of the test. So if you are looking at this 10 weeks from now make sure you scroll to the bottom and grab the most recent test.
这是测试的第 16 版。因此,如果您正在查看这 10 周后的内容,请确保滚动到底部并获取最近的测试。
回答by james2doyle
The switch
statement is more efficient/expressive than if/else
in some cases. While the following if/else
statement
该switch
语句比if/else
某些情况下更有效/更具表现力。虽然下面的if/else
语句
let x = 123;
if (x) {/*...*/} // implicit type casting (to boolean)
else {/*...*/}
can be easily converted to:
可以很容易地转换为:
switch (!!x) { // explicit type casting (to boolean)
case true: /*...*/ break;
default: /*...*/
}
this switch
statement on the other hand
switch
另一方面,这个声明
function algo(x) {/*...performing a complex algorithm...*/}
switch (algo(123)) { // executed once
case "result 1": /*...*/ break;
case "result 2": /*...*/ break;
case "result 3": /*...*/ break;
default: /*...*/
}
results in an incredible inefficient if/else
statement (switch
is more efficient):
导致令人难以置信的低效if/else
语句(switch
效率更高):
if (algo(123) === "result 1") {/*...*/}
else if (algo(123) === "result 2") {/*...*/}
else if (algo(123) === "result 3") {/*...*/}
else {/*...*/}
or requires an if/else
with additional variable, which is declared for this purpose exclusively:
或需要一个if/else
with 附加变量,专门为此目的声明:
let y = algo(x); // additional variable
if (y === "result 1") {/*...*/}
else if (y === "result 2") {/*...*/}
else if (y === "result 3") {/*...*/}
else {/*...*/}
Please note that additional elements (like variables) cause more complexity and complexity makes programs more error prone. The switch
statement doesn't need such a variable, because it is more expressive.
请注意,额外的元素(如变量)会导致更多的复杂性,而复杂性会使程序更容易出错。该switch
声明并不需要这样的变量,因为它是更具表现力。
回答by Charlie Kilian
If you go with the if statement, I personally prefer setting default values above the if, like this:
如果您使用 if 语句,我个人更喜欢在 if 之上设置默认值,如下所示:
is_valid.accepted = false;
if(message == 'redirect')
{
is_valid.accepted = true;
}
That way, you always default to a safe behavior that is less likely to break if you add more options later on. Also, you see the default behavior at a glance without having to read through the if-then-else logic. And it's much shorter code.
这样,您始终默认采用安全行为,如果稍后添加更多选项,则不太可能破坏该行为。此外,您可以一目了然地看到默认行为,而无需通读 if-then-else 逻辑。它的代码要短得多。
回答by Winfield Trail
Switch is better if you're working with a long list of possible conditions on the same variable. In this case, I don't think there's much reason to use switch() unless you prefer the syntax.
如果您在同一变量上处理一长串可能的条件,则 Switch 会更好。在这种情况下,除非您更喜欢这种语法,否则我认为没有太多理由使用 switch()。
回答by Shaz
Ternary?
is_valid.accepted = (message !== 'invalid id') ? true : false;
三元?
is_valid.accepted = (message !== 'invalid id') ? true : false;