当前位置:网站首页>There are four ways to write switch, you know
There are four ways to write switch, you know
2022-07-01 20:28:00 【51CTO】
JavaScript Of switch There are four ways to write , Do you know? ? Whether you know it or not , Anyway, I don't know .
What I know JavaScript Of switch There is only one way to write a sentence . But when it comes to dealing with branches , There are many ways to write .if The branch writing method can be regarded as one ,switch Branch writing can be regarded as the second , The third is to use the strategy mode , If you want to count conditional operators , Um. , Just four .
But the main character of this article is switch. Everyone knows switch Generally speaking, the way of writing is switch Variable or expression ,case Constant . Um. , for instance , A hundred mark mark ,90 And 90 A score above is excellent ,80 And above 90 The following is good ,60 And above 80 The following is qualified ,60 The following are unqualified , use switch I'll probably say that :
In the code
score / 10 | 0 and Math.floor(score / 10) It's the same effect , Is divided by 10 Take the integer part of the quotient .
This paragraph switch Well done , Use rounding to avoid using a long string if ... else Branching is also a coincidence .
But now the rules have changed , Separate qualified and good points from 80 The score dropped to 75 branch , What should I do ?
The rounding method above is still ok , But this time the divisor is no longer 10, It is 5. Accordingly ,case A lot more :
- 18、19、20 It's excellent
- 15、16、17 Is good
- 12、13、14 It's qualified
- The rest is unqualified
Write 9 individual case, It's better to use if ... else Forget it .
Is it? ? Actually use switch There are also simpler ways to write :
Does it feel strange ? This is not used to at all switch expression case Constant , It's the opposite ,switch Constant case expression ! If you take this program to run , There will be no problem at all . because ——switch and case Is in accordance with the === To match , It doesn't care whether it's an expression or a constant , Or say ,switch and case Expressions can be followed !
Yes , expression !
So in the example above , hold switch(true) Change to switch( 2 > 1) The same effect .
All right. , Brain hole is open .switch It doesn't matter how many ways to write . The next thing to study is switch Variants ——
notice C# Yes switch expression , be envious , Can it be realized? ?
Don't be greedy ,JavaScript Everything in can be an expression …… If not , use IIFE Just encapsulate one
Pay attention to the score As IIFE Parameters of , Because in actual use , What you may need to pass in is an expression . In this case, it should be evaluated in advance , And only once ( Avoid the side effects of substitution ).
However, such encapsulation is obviously meaningless , If you really want to package like this , It's better to seal it into a strategy :
Every strategy contains tester (t) And the value (v) The object of .tester Is a judgement function , Pass in the value to be judged , That is to say switch ( expression ) Here the expression , And this expression is evaluated in advance as IIFE Is passed in . The process of applying strategies is simple and crude , Is to find the first qualified strategy , Take its value .
Of course, this strategy is a little overqualified . Situations that really need strategies , There is usually not a value in the policy , It's an act , That is, function .
We know that switch In the sentence , each case Are in the same scope , So it can't be in two case Statement to declare the same local variable . Although with { } Packages can solve these problems , But the code doesn't look very good , In particular, be careful not to forget break. If you use strategy , It may look pleasant , And don't worry about it break The problem of :
Here's a demonstration , Results will be output first in strategic behavior , Return to level .
function
calcGrade(
score) {
return ((
value,
rules)
=>
rules.
find(({
t })
=>
t(
value)).
fn(
value))(
score,
[
{
t:
n
=>
n
>=
90,
fn:
score
=> {
const
grade
=
" good ";
console.
log(
grade,
score);
return
grade;
}
},
{
t:
n
=>
n
>=
75,
fn:
score
=> {
const
grade
=
" good ";
console.
log(
grade,
score);
return
grade;
}
},
{
t:
n
=>
n
>=
60,
fn:
score
=> {
const
grade
=
" qualified ";
console.
log(
grade,
score);
return
grade;
}
},
{
t: ()
=>
true,
fn:
score
=> {
const
grade
=
" unqualified ";
console.
log(
grade,
score);
return
grade;
}
},
]
);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
The code is really a little long , Because there is strategic behavior logic in it . If you really want to be switch expression To use , The policy part should be an expression , It won't be long . In the above code , Strategy behavior is similar , Can be encapsulated into a function , In this way, it can be written in the form of an expression :
function
calcGrade(
score) {
const
printGrade
= (
grade,
score)
=> {
console.
log(
grade,
score);
return
grade;
};
return ((
value,
rules)
=>
rules.
find(({
t })
=>
t(
value)).
fn(
value))(
score,
[
{
t:
n
=>
n
>=
90,
fn:
score
=>
printGrade(
" good ",
score) },
{
t:
n
=>
n
>=
75,
fn:
score
=>
printGrade(
" good ",
score) },
{
t:
n
=>
n
>=
60,
fn:
score
=>
printGrade(
" qualified ",
score) },
{
t: ()
=>
true,
fn:
score
=>
printGrade(
" unqualified ",
score) },
]
);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
Does it look decent now ?
The code above has different forms , It's all about the same thing , There is no comparison between who is good and who is bad . It looks good, but it's elegant , I don't like it. I'm not favored . In different circumstances , Just choose the right approach . The code above uses find() To find strategies , If you switch to filter(), That would be another scene ~(~ ̄▽ ̄)~.
边栏推荐
- 如何用OpenMesh创建一个四棱锥
- EURA欧瑞E1000系列变频器使用PID实现恒压供水功能的相关参数设置及接线
- SQL getting started plan-1-select
- #yyds干货盘点#SQL聚合查询方法总结
- 8K HDR!| Hevc hard solution for chromium - principle / Measurement Guide
- 网上开户是安全的吗?新手可以开炒股账户吗。
- Iframe parent-child page communication
- Is it safe to open an account online? Can a novice open a stock trading account.
- On the usage of a magic function
- Develop those things: easycvr cluster device management page function display optimization
猜你喜欢

Penetration tools - trustedsec's penetration testing framework (PTF)

EasyCVR通过国标GB28181协议接入设备,出现设备自动拉流是什么原因?

Simple but modern server dashboard dashdot

Use of common built-in classes of JS

On the next generation entrance of the metauniverse -- the implementation of brain computer interface

math_利用微分算近似值

What if the win11 shortcut key switching input method doesn't respond? Shortcut key switching input method does not respond
![[mysql] install mysql5.7](/img/c4/d7fb5ddf8e7be31f7a9ad68409e584.png)
[mysql] install mysql5.7

Data analysts sound tall? Understand these points before you decide whether to transform

Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers
随机推荐
寫博客文檔
如何用OpenMesh创建一个四棱锥
Oracle deadlock test
Importance of EDA tools to chip industry knowledge popularization
【多线程】锁策略
Win11快捷键切换输入法无反应怎么办?快捷键切换输入法没有反应
3D全景模型展示可视化技术演示
Entering Ruxin Town, digital intelligence transformation connects "future community"
Understand the structure in C language in one article
Solve the problem of slow or failed vscode download
强大、好用、适合程序员/软件开发者的专业编辑器/笔记软件综合评测和全面推荐
Tensorflow reports an error, could not load dynamic library 'libcudnn so. eight
【多线程】 实现单例模式 ( 饿汉、懒汉 ) 实现线程安全的单例模式 (双重效验锁)
目标检测——Yolo系列
fastDFS入门
1592 example 1 King (sgu223 loj10170 luogu1896 increase + / provincial election -) violent thinking pressure DP 01 Backpack
开发那些事儿:EasyCVR集群设备管理页面功能展示优化
走进如心小镇,数智化变革连接“未来社区”
渗透工具-TrustedSec 公司的渗透测试框架 (PTF)
How can I know if I want to get the preferential link of stock account opening? Is it safe to open an account online?