当前位置:网站首页>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 ~(~ ̄▽ ̄)~
.
边栏推荐
- 利用QEventLoop实现同步等待槽函数返回
- 编译原理复习笔记
- Keras机器翻译实战
- Architect graduation summary
- 渗透工具-TrustedSec 公司的渗透测试框架 (PTF)
- list分割成满足和不满足条件的集合(partitioningBy)
-
- 开发那些事儿:EasyCVR平台添加播放地址鉴权功能
- GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
- Easycvr accesses the equipment through the national standard gb28181 protocol. What is the reason for the automatic streaming of the equipment?
猜你喜欢
实战项目笔记(一)——虚拟机的创建
独家消息:阿里云悄然推出RPA云电脑,已与多家RPA厂商开放合作
[multithreading] realize the singleton mode (hungry and lazy) realize the thread safe singleton mode (double validation lock)
Servlet knowledge points
【多线程】 实现单例模式 ( 饿汉、懒汉 ) 实现线程安全的单例模式 (双重效验锁)
1592 example 1 King (sgu223 loj10170 luogu1896 increase + / provincial election -) violent thinking pressure DP 01 Backpack
MYSLQ十种锁,一篇文章带你全解析
Items in richview documents
Entering Ruxin Town, digital intelligence transformation connects "future community"
目标检测——Yolo系列
随机推荐
如何用OpenMesh创建一个四棱锥
【多线程】 实现单例模式 ( 饿汉、懒汉 ) 实现线程安全的单例模式 (双重效验锁)
寫博客文檔
开发那些事儿:EasyCVR集群设备管理页面功能展示优化
Common components of flask
想得到股票开户的优惠链接,如何得知?在线开户是安全么?
Simple but modern server dashboard dashdot
C#聯合halcon應用——大華相機采集類
3D全景模型展示可视化技术演示
Using qeventloop to realize synchronous waiting for the return of slot function
Understand the structure in C language in one article
Realize pyramids through JS (asterisk pyramid, palindrome symmetric digital pyramid)
PHP gets the external chain address of wechat applet and applet store
网上开户是安全的吗?新手可以开炒股账户吗。
Win11快捷键切换输入法无反应怎么办?快捷键切换输入法没有反应
【let var const】
渗透工具-TrustedSec 公司的渗透测试框架 (PTF)
【多线程】锁策略
What if win11 can't pause the update? Win11 pause update is gray. How to solve it?
关于元宇宙下一代入口——脑机接口的实现