本文共 1589 字,大约阅读时间需要 5 分钟。
An if/else
statement is great when you have a few options to choose.
当您有一些选择时, if/else
语句非常有用。
When they are too many however it might be overkill. Your code will look too complex.
但是,当它们太多时,可能就太过分了。 您的代码看起来太复杂了。
In this case you might want to use a switch
conditional:
在这种情况下,您可能需要使用条件switch
:
switch() { //cases}
based on the result of the expression, JavaScript will trigger one specific case you define:
根据表达式的结果,JavaScript将触发您定义的一种特定情况:
const a = 2switch(a) { case 1: //handle case a is 1 break case 2: //handle case a is 2 break case 3: //handle case a is 3 break}
You must add a break
statement at the bottom of each case, otherwise JavaScript will also execute the code in the next case (and sometimes this is useful, but beware of bugs). When used inside a function, if the switch defines a return value, instead of using break
you can just use return
:
您必须在每种情况的底部添加一个break
语句,否则JavaScript也会在下一种情况下执行代码(有时这是有用的,但是要注意错误)。 在函数内部使用时,如果开关定义了返回值,则可以使用return
来代替使用break
:
const doSomething = (a) => { switch(a) { case 1: //handle case a is 1 return 'handled 1' case 2: //handle case a is 2 return 'handled 2' case 3: //handle case a is 3 return 'handled 3' }}
You can provide a default
special case, which is called when no case handles the result of the expression:
您可以提供default
特殊情况,当没有大小写处理表达式的结果时调用该特殊情况:
const a = 2switch(a) { case 1: //handle case a is 1 break case 2: //handle case a is 2 break case 3: //handle case a is 3 break default: //handle all other cases break}
翻译自:
转载地址:http://lvqgb.baihongyu.com/