Node.JS 中的 switch 与 if-else 分支控制结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15831579/
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
switch vs if-else branching control structure in Node.JS
提问by Amol M Kulkarni
Which one is good to use when there is a large number of branching flow in Node.JS Program.
Node.JS程序中有大量分支流的时候用哪个好。
switch
转变
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
OR
if-else
或
if-else
if (condition1)
{
execute code block 1
}
else if(condition2)
{
execute code block 2
}
else
{
code to be executed if n is different from condition1 and condition2
}
回答by pkp
For just a few items, the difference is small. If you have many items you should definitely use a switch. It give better performance than if-else.
对于少数项目,差异很小。如果您有很多物品,则绝对应该使用开关。它提供比 if-else 更好的性能。
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if-else where the last item takes much more time to reach as it has to evaluate every previous condition first..
如果开关包含五个以上的项目,则使用查找表或哈希列表来实现。这意味着所有项目都获得相同的访问时间,与 if-else 列表相比,最后一个项目需要更多时间才能到达,因为它必须首先评估每个先前的条件。
回答by upendra patil
switch(n)
{
case 1,3,4:
execute code block 1
break;
case 2,5,9,10:
execute code block 2
break;
default:
code to be executed if n is different from first 2 cases.
}
To write down the if...else if...else steps for the above case, you will have to write the 'OR (||)' condition-statement and repeat the variable 'n' in the statement, Where as switch cases can be separated by just a comma ','. Thus switch is more readable for such a case.
要写下上述情况的 if...else if...else 步骤,您必须编写 'OR (||)' 条件语句并在语句中重复变量 'n',Where as switch案例可以仅用逗号“,”分隔。因此,对于这种情况, switch 更具可读性。

