当前位置:网站首页>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 ~(~ ̄▽ ̄)~
.
边栏推荐
- Solve the problem of slow or failed vscode download
- internship:逐渐迈向项目开发
- Niuke programming question -- must brush the string of 101 (brush the question efficiently, draw inferences from one instance)
- Keras机器翻译实战
- Oracle 死锁测试
- Detailed explanation and code example of affinity propagation clustering calculation formula based on graph
- Easycvr accesses the equipment through the national standard gb28181 protocol. What is the reason for the automatic streaming of the equipment?
- The large list set is divided into multiple small list sets in equal proportion
- Myslq ten kinds of locks, an article will take you to fully analyze
- Win11快捷键切换输入法无反应怎么办?快捷键切换输入法没有反应
猜你喜欢
Common components of flask
3D panoramic model display visualization technology demonstration
[Mysql]安装Mysql5.7
Flask 常用组件
Learn white box test case design from simple to deep
Items in richview documents
Win11如何取消任务栏隐藏?Win11取消任务栏隐藏的方法
Win11怎么关闭开机自启动软件
Detailed configuration of network security "Splunk" in national vocational college skills competition
如何用OpenMesh创建一个四棱锥
随机推荐
Win11暂停更新点不了怎么办?Win11暂停更新是灰色的如何解决?
Develop those things: easycvr platform adds playback address authentication function
Stack overflow 2022 developer survey: where is the industry going?
docker ubuntu容器中安装mysql遇到的问题
C#联合halcon应用——大华相机采集类
Understand the structure in C language in one article
Big factories are wolves, small factories are dogs?
开发那些事儿:EasyCVR平台添加播放地址鉴权功能
Iframe 父子页面通信
渗透工具-TrustedSec 公司的渗透测试框架 (PTF)
uniapp使用腾讯地图选点 没有window监听回传用户的位置信息,怎么处理
[Blue Bridge Cup web] analysis of the real topic of the 13th Blue Bridge Cup web university group match in 2022
关于一个神奇函数的用法
What else do you not know about new set()
Keras machine translation practice
What if win11 can't pause the update? Win11 pause update is gray. How to solve it?
Related concepts of cookies and sessions
Redis installation and startup in Windows environment (background startup)
Myslq ten kinds of locks, an article will take you to fully analyze
Oracle 死锁测试