本文共 6604 字,大约阅读时间需要 22 分钟。
The is indispensable for certain programming tasks. In this article, you’ll learn how to use switch
and hopefully gain the intuition to know when you should use it.
对于某些编程任务是必不可少的。 在本文中,您将学习如何使用switch
并希望获得直觉,以了解何时应该使用它。
A telltale sign to use switch
is when you have a lot of consecutive if/else
statements. Let’s look at an example using if/else
, and then we’ll look at the switch
equivalent for comparison:
当您有很多连续的if/else
语句时,要使用switch
标志就是。 让我们看一下使用if/else
的示例,然后看一下等效的switch
以进行比较:
let dayIndex = new Date().getDay();let day;if (dayIndex === 0) { day = 'Sunday';}else if (dayIndex === 1) { day = 'Monday';}else if (dayIndex === 2) { day = 'Tuesday';}else if (dayIndex === 3) { day = 'Wednesday';}else if (dayIndex === 4) { day = 'Thursday';}else if (dayIndex === 5) { day = 'Friday';}else if (dayIndex === 6) { day = 'Saturday';};console.log(day); // "Friday"
Did you know? JavaScript doesn’t have a native method to get the day of the week!
你知道吗? JavaScript没有本机方法来获取星期几!
Using if/else
is really verbose, and contains a lot of unnecessary boilerplate that switch
can handle with ease:
使用if/else
确实很冗长,并且包含很多不必要的样板,可以轻松地进行switch
:
let dayIndex = new Date().getDay();let day;switch (dayIndex) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; break;};console.log(day); // "Friday"
There’s barely any code, and it’s refreshingly minimal. This is because switch
places emphasis on the possible values instead of the conditions for the values.
几乎没有任何代码,而且令人耳目一新。 这是因为switch
着重于可能的值而不是值的条件 。
Since JavaScript will navigate through the entire case
branch many times it’s advisable to use break
to prevent unexpected case
matches or to save the engine from having to parse extra code.
由于JavaScript会多次遍历整个case
分支,因此建议使用break
来防止意外的case
匹配,或者避免引擎不得不解析额外的代码。
switch (dayIndex) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; break;}
In this example, break
doesn’t actually provide any added safety since case 2
can never be case 5
(for example) so break
is somewhat extraneous. This rigorous usage of break
seems to be a preferential matter among developers like the usage of semicolons (;). Developers that take an explicit approach to programming will use break
for every case
, while some developers only use break
strategically in switch
. There’s a slight performance gain from using it across the board however, because even if there’s no chance for another case to be true, at least you won’t even have the engine run through the rest of the switch statement.
在此示例中, break
实际上并没有提供任何额外的安全性,因为case 2
永远不会成为case 5
(例如),因此break
有些多余。 像分号(;)一样,严格使用break
似乎是开发人员的优先事项。 采用显式编程方式的开发人员将在任何case
都使用break
,而有些开发人员仅在switch
时有策略地使用break
。 但是,由于全盘使用它会带来一点性能提升,因为即使没有其他情况发生的机会,至少您甚至不会在switch语句的其余部分运行引擎。
Sometimes you’ll actually want your cases to “fall through”. Using break
for these instances is more of a strategy than a safety measure.
有时,您实际上会希望您的案件“失败”。 对于这些情况,使用break
更多是一种策略,而不是安全措施。
let seasonIndex = new Date().getMonth();let season;switch (seasonIndex) { case 0: case 1: case 2: season = 'Winter'; // January, February, March break; case 3: case 4: case 5: season = 'Spring'; // April, May, June break; case 6: case 7: case 8: season = 'Summer'; // July, August, September break; case 9: case 10: case 11: season = 'Autumn'; // October, November, December break;}
In this example, the cases are “falling through” and break
is used to explicitly exit switch
early. This allows you to lump several cases together with a single value.
在此示例中,案例“陷入困境”,并且使用break
来显式退出switch
。 这使您可以将多个个案与单个值一起处理。
The if/else
version would require using lots of ||
logical operators which doesn’t seem as transparent:
if/else
版本将需要使用许多||
似乎不透明的逻辑运算符:
if (seasonIndex === 0 || seasonIndex === 1 || seasonIndex === 2) { season = 'Winter'; } else if (seasonIndex === 3 || seasonIndex === 4 || seasonIndex === 5) { season = 'Spring'; } else if (seasonIndex === 6 || seasonIndex === 7 || seasonIndex === 8) { season = 'Summer'; } else if (seasonIndex === 9 || seasonIndex === 10 || seasonIndex === 11) { season = 'Fall'; }
Another feature of switch
is the ability to handle unexpected or generic cases. Returning to our first example, we can use default
to implement error handling:
switch
另一个功能是能够处理意外或一般情况。 回到我们的第一个示例,我们可以使用default
来实现错误处理:
let dayIndex = new Date().getDay();let day;switch (dayIndex) { default: day = new Error('Invalid argument: "dayIndex" must be an integer from 0 –> 6'); case 0: day = 'Sunday'; break; case 1: day = 'Monday'; break; case 2: day = 'Tuesday'; break; case 3: day = 'Wednesday'; break; case 4: day = 'Thursday'; break; case 5: day = 'Friday'; break; case 6: day = 'Saturday'; break;}
You might have noticed that the default
case is placed at the top. Not to worry! It’ll work as expected because JavaScript will look through all the case
branches before it settling on default
.
您可能已经注意到default
案例位于顶部。 不要担心! 它会按预期工作,因为JavaScript将在default
之前浏览所有case
分支。
You can also use default
for your generic cases:
您还可以将default
用于一般情况:
let beverage = 'Mr. Pibb';let cost;switch (beverage) { default: cost = 0.05; case 'Pepsi': cost = 1.00; break; case 'Coca-Cola': cost = 1.00; break; case 'Dr. Pepper': cost = 2.00; break; case 'Moutain Dew': cost = 5.00; break;}console.log(cost); // 0.05
This ensures you’ll get some sorta value from switch
even if it doesn’t match any of your defined cases
.
这样可以确保您从switch
得到某种sorta值,即使它与您定义的cases
都不匹配。
Switch statements are an elegant alternative when you find yourself writing a lot of consecutive if/else
statements. Even though you may not use switch
as often as, say, a for-loop
there’s no substitute when you need it. Modern libraries libraries like and still use switch
today, making it one of those old-school workhorse features of JavaScript you’ll always need to keep under your belt.
当您发现自己编写大量连续的if/else
语句时,switch语句是一种不错的选择。 即使您可能不像使用for-loop
那样频繁使用switch
,但是在您需要时没有替代品。 如今,诸如和类的现代图书馆库仍在使用switch
,这使其成为您始终需要掌握JavaScript的老派功能之一。
To learn more about switch
visit the website.
要了解有关switch
更多信息,请访问网站。
翻译自:
转载地址:http://nshgb.baihongyu.com/