在JavaScript中优化switch语句

The switch statement 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语句对于某些编程任务是必不可少的。 在本文中,您将学习如何使用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 着重于可能的值而不是值的条件 。

使用休息 (Using break)

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语句的其余部分运行引擎。

“突破”的战略用途 (The Strategic Use of “break”)

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';
 }

处理默认案例 (Handling Default Cases)

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都不匹配。

结论 (Conclusion)

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 Lodash and Redux 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 ,但是在您需要时没有替代品。 如今,诸如LodashRedux之类的现代图书馆库仍在使用switch ,这使其成为您始终需要掌握JavaScript的老派功能之一。

To learn more about switch visit the Mozilla Developer website.

要了解有关switch更多信息,请访问Mozilla Developer网站。

翻译自: https://www.digitalocean.com/community/tutorials/js-optimizing-switch-statement

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值