javascript开关_JavaScript开关案例简介
javascript开关
In this short article, I will introduce you to JavaScript switch cases and how to use them with practical examples.
在这篇简短的文章中,我将向您介绍JavaScript切换案例以及如何通过实际示例使用它们。
This article will explain better with more practical examples to help you understand switch cases in depth.
本文将通过更实际的示例更好地解释,以帮助您深入了解切换案例。
先决条件。 (Prerequisites.)
- Basic JavaScript knowledge基本JavaScript知识
- Code editor代码编辑器
- Web Browser网页浏览器
- Your brain :)你的脑 :)
A switch
statement can basically replace multiple if
checks in JavaScript.
if
在JavaScript中进行检查, if
switch
语句基本上可以替换多个语句。
It gives a more descriptive way to compare a value with multiple variants.
它提供了一种更具描述性的方式来将值与多个变量进行比较。
开关语法 (The Switch Syntax)
The switch
has one or more case
blocks and an optional default case.
switch
具有一个或多个case
框和一个可选的默认大小写。
switch(x) {case 'value1': // if (x === 'value1')//code here[break]case 'value2': // if (x === 'value2')//code here[break]default://code here[break]
}
The value of
x
is checked for strict equality to the value from the firstcase
(that is,value1
) then to the second (value2
) and so on.检查
x
的值是否严格等于从第一种case
(即value1
)到第二种情况(value2
)的value2
,依此类推。If the equality is found,
switch
starts to execute the code starting from the correspondingcase
, until the nearestbreak
(or until the end ofswitch
).如果找到相等,则
switch
从相应的case
开始执行代码,直到最近的break
(或直到switch
结束)。If no case is matched then the
default
code is executed (if it exists).如果没有大小写匹配,则执行
default
代码(如果存在)。
一些真实的例子 (Some few real examples)
Simple Play & Pause Switch
简单播放和暂停开关
The switch
statement can be used for multiple branches based on a number or string:
switch
语句可用于基于数字或字符串的多个分支:
switch (movie) {case 'play':playMovie();break;case 'pause':pauseMovie();break;default:doNothing();
}
If you don’t add a break
statement, the execution will "fall through" to the next level. It's essential that you deliberately label the fall through with a comment if you really meant it to aid debugging:
如果不添加break
语句,执行将“下降”到下一个级别。 如果您确实要帮助调试,请务必在注释中故意标记掉处:
switch (movie) {case 'play': // fallthroughcase 'pause':pauseMovie();break;default:doNothing();
}
The default clause is optional. You can have expressions in both the switch part and the cases if you like; comparisons take place between the two using the ===
operator:
默认子句是可选的。 如果愿意,您可以在switch部分和case中都有表达式; 使用===
运算符在两者之间进行比较:
switch (3 + 7) {case 5 + 5:correct();break;default:neverhappens();
}
Simple Maths Calc Switch
简单的数学计算开关
let average = 2 + 6;switch (average) {case 4:alert( 'Too small' );break;case 8:alert( 'Exactly!' );break;case 10:alert( 'Too large' );break;default:alert( "Incorrect values!" );
}
Here the switch
starts to compare average
from the first case
variant that is 4
. The match fails.
在此, switch
开始比较第一种case
average
4
。 比赛失败。
Then 8
. That’s a match, so the execution starts from case 8
until the nearest break
.
然后8
。 这是一个匹配,因此执行从case 8
开始,直到最近的break
为止。
If there is no break
then the execution continues with the next case
without any checks.
如果没有 break
则继续执行下 case
不进行任何检查。
Here is an example without break
:
这里有没有一个例子break
:
let average = 2 + 6;switch (average) {case 4:alert( 'Too small' );case 8:alert( 'Exactly!' );case 10:alert( 'Too big' );default:alert( "Incorrect values!" );
}
In the example above we’ll see sequential execution of three alerts
:
在上面的示例中,我们将看到三个alerts
顺序执行:
alert( 'Exactly!' );
alert( 'Too big' );
alert( "Incorrect values!" );
getDay() method switch case
getDay()方法切换案例
The getDay()
method returns the weekday as a number between 0 and 6.
getDay()
方法以0到6之间的数字返回工作日。
Sunday=0, Monday=1, Tuesday=2 , Wednesday=3, Thursday=4, Friday=5, Saturday=6
周日= 0,周一= 1,周二= 2,周三= 3,周四= 4,周五= 5,周六= 6
This example uses the weekday number to calculate the weekday name:
本示例使用工作日编号来计算工作日名称:
switch (new Date().getDay()) {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";
}
The result of day will be the current weekday in day format
日的结果将是日格式的当前工作日
PS: This would change according to when you’re reading this article
PS:这将根据您阅读本文的时间而改变
I wrote this artcle on 13/06/2019 which is a Thursday, so the result would be:
我在2019年6月13日(星期四)写了这篇文章,结果将是:
Thursday
默认关键字 (The default Keyword)
The default keyword specifies the code to run if there is no case match, more like an else statement:
default关键字指定在没有大小写匹配的情况下要运行的代码,更类似于else语句:
switch (new Date().getDay()) {case 6:text = "Today is Saturday";break; case 0:text = "Today is Sunday";break; default: text = "Its not weekend yet!";
}
The result of text will be:
文本结果将是:
Its not weekend yet!
The default case does not have to be the last case in a switch block:
默认大小写不必一定是switch块中的最后一个大小写:
switch (new Date().getDay()) {default: text = "Its not weekend yet!";break;case 6:text = "Today is Saturday";break; case 0:text = "Today is Sunday";
}
If default is not the last case in the switch block, remember to end the default case with a break.
如果默认值不是切换块中的最后一种情况,请记住以默认值结尾。
结论 (Conclusion)
There are so many practical examples of switch cases, you can head over to google.com and run a quick search for more switch cases examples.
切换案例的实用示例如此之多,您可以转到google.com并快速搜索更多切换案例的示例。
If this article helped you, show it by sharing.
如果这篇文章对您有所帮助,请通过共享进行展示。
Thanks for reading!
谢谢阅读!
翻译自: https://www.freecodecamp.org/news/introduction-to-javascript-switch-cases/
javascript开关
相关文章:

C++中一个class类对象占用多少内字节(7个例子,很清楚)
一个空的class在内存中多少字节?如果加入一个成员函数后是多大?这个成员函数存储在内存中什么部分? 一个Class对象需要占用多大的内存空间。最权威的结论是: *非静态成员变量总合。 *加上编译器为了CPU计算,作出的数据…

Java学习----到底调用哪一个方法(多态)
public class Father {public void print() {System.out.println("Father:print()");} } public class Son extends Father{// 方法的覆盖:子类重写父类的同名方法 Overridepublic void print() {System.out.println("Son:print()");}// Father…

mpvue 转uni-app 操作记录
1.创建一个uni-app 的项目,把原有的mpvue项目手动迁移过来 2.用到mpvue特性的代码,需要修改成uni-app 兼容的,例如 mpvue-wxparse 可以修改成 3.src/app.json 改成 pages.json ,路径格式需要改,如下格式 {"pages": [&…

桌面应用程序 azure_Azure Logic应用程序用例–黑色星期五
桌面应用程序 azureThis blog gives an overview of how Azure Serverless technologies came to rescue when the custom-built integration system went down. Also, it shows the high-level architecture solution built using Azure Serverless services like Logic Apps,…

PHP的静态变量介绍
静态变量只存在于函数作用域内,也就是说,静态变量只存活在栈中。一般的函数内变量在函数结束后会释放,比如局部变量,但是静态变量却不会。就是说,下次再调用这个函数的时候,该变量的值会保留下来。 只要在变…

MySQL 解压版创建用户密码
root 权限进入MySQL: mysql –uroot 查看当前MySQL用户: select user,host from mysql.user; 此处以User为root,Host为localhost的账户为例,将密码改为password的命令: SET PASSWORD FOR rootlocalhost PASSWORD(newp…

git 忽略指定文件夹的上传
我们在使用 git 开发的时候,有些插件的模块文件通过npm install 就可以下载,一般是不上传到 git 中的(因为文件太多会导致很耗时),例如 我的 node_modules 文件夹,不想上传,我们应该这么做。 我们需要创建一…

数据库初学者_面向初学者的免费6小时数据科学课程
数据库初学者Data science is considered the "sexiest job of the 21st century." Learn data science in this full 6-hour course for absolute beginners from Barton Poulson of datalab.cc.数据科学被认为是“ 21世纪最艰巨的工作”。 通过datalab.cc的 Barton…

网页抓取及下载
downAndroidApk.php <?php /* 命令行 d: cd ApacheServer\php php.exe D:\ApacheServer\web\crawl\downAndroidApk.php --appidFileD:\ApacheServer\web\crawl\youxi.txt --newDirD:\ApacheServer\web\crawl\requestNewDir*/ // 判断必须在php-cli模式下运行,即…

javascript中关于this指向问题详解
前 言 LiuDaP 在前端的学习中,我们必然要用到js,js可以说是前端必不可少的的东西。在学习js的过程中,我们会经常用到this这个东西,而this的指向问题就变得尤为重要。今天正好有空闲时间,就给大家详细介绍一下js中关于…

mpvue 转uniapp 导航栏样式错乱问题修复 tabbar 样式修复
效果图:修改前,修改后 找了半天没找到原因,只能自己改样式了,下面是样式代码(在app.vue 里面加上就行) <style>/*每个页面公共css */uni-tabbar {box-sizing: border-box;position: fixed;left: 0;bo…

css规则_CSS规则,将使您的生活更轻松
css规则by Nick Gard尼克加德(Nick Gard) CSS规则,将使您的生活更轻松 (CSS rules that will make your life easier) After years of writing and maintaining a couple of very large web projects and numerous smaller ones, I have developed some heuristics…

在mybatis中模糊查询有三种写法
<select id"selectStudentsByName" resultType"Student"> <!--第一种--> <!-- select id,name,age,score from student where name like % #{0} % --> <!--第二种--> <!-- select id,name,age,score from student wher…

BZOJ 3566: [SHOI2014]概率充电器
题目:http://www.lydsy.com/JudgeOnline/problem.php?id3566 首先这题正着想不好想,考虑补集转化。 先dfs一遍,令f[u](1-p[u])*∏(1-(1-f[v])*w) f[u]表示u这个点通过其子树并不能联通的概率。 然后考虑v从其父亲连过来的情况,设…

小程序云开发,订阅消息定时批量发送实现代码
需求:做一个类似抽奖结果通知的订阅消息提醒 实现流程: 每个用户需要先授权订阅消息接收,授权成功后把数据存到云开发的数据集合里面,再写个定时器,遍历数据集合的所有数据,拿到后遍历发送订阅消息&#…

机器学习速成课程
Learn the basics of machine learning and data science in this crash course tutorial for beginners from AI Sciences Academy. This course will give you the foundation you need to start learning more advanced material.在此速成课程教程中为AI Sciences Academy的…

H5 画布解决跨域问题,画布保存为图片显示在页面上
实现功能:uniapp H5 使用画布,绘画完之后保存为图片全屏显示完整实现代码,跨域解决方案。 跨域图片解决方案一:(使用base64编码)网络图片放到画布里面绘画 跨域图片解决方案二:(使…

1、IO输入输出流 简介
IO流的分类: * 流向: * 输入流 读取数据 * 输出流 写出数据 * 数据类型: * 字节流 * 字节输入流 读取数据 InputStream * 字节输出流 写出数据 OutputStream * 字符流 * 字符输入流 读取数据 Reader * 字符输出流 写出数据 Writer * * 注意&…

mern技术栈好处?_通过构建运动追踪器应用程序来学习MERN堆栈(MERN教程)
mern技术栈好处?The MERN stack is a popular stack of technologies for building a modern single-page application. In this video course I developed, you will learn the MERN stack by building a full stack exercise tracker application.MERN堆栈是用于构建现代单页…

使用html5进行视频播放
一直以来网页大多是使用 flash 来播放视频。在目前唱衰 flash 的环境下,HTML5 为我们带来了一个网页内视频播放的解决方案—— <video>标签。 在HTML5 中,可以通过HTML标签“audio”和“video”来支持嵌入式的媒体,使开发者能够方便地将…

Linux学习之系统时间同步
一、系统时间的设置 在Linux中设置系统时间,可以用date命令: 1 //查看时间 2 [rootlocalhost ~]# date 3 2008年 12月 12日 星期五 14:44:12 CST 4 //修改时间 5 [rootlocalhost ~]# date --set "1/1/09 00:01" < (月/日/年时:分…

uniapp(一) 项目架构,封装
前言: 最近需要搭建一套基于uniapp 的代码模板,适应各平台的快速打包部署,为提高代码复用率,提升生产力,所以需要构建一套优雅的前端项目架构,下面分享记录一下我的封装。 代码封装我暂时分为三个层面&…

linux下安装sbt_如何在Linux上安装SBT
linux下安装sbt介绍 (Introduction) Hi! I am Sanjula, and in this guide I hope to teach you how to install sbt on Linux.嗨! 我是Sanjula ,我希望在本指南中教您如何在Linux上安装sbt。 Let’s get started!让我们开始吧! 什么是sbt&…

switch...case结构
/**switch(要判断的数据){ case 值1: ...;break; case 值2: ...;break; case 值3: ...;break; default: ...;break;}*/ publuc class employee{ int id; // 员工id String name; // 员工名字 int age; // 员工年龄 String phone; // 员工号码 String address; // 员工地址 publ…

自动布局的 弊端 (后续)
自动布局 比 直接写 frame 会慢很多 具体以后再说吧转载于:https://www.cnblogs.com/Ionatan/p/5109211.html

uniapp H5 JSSDK封装使用
先看效果吧, 封装以后使用很方便,两行代码就能得到微信网页开发中的 jssdk 的 wx.config 执行了 wx.ready 还是 wx.error ,如果返回 true 就标识执行了ready , 可以调用JSSDK的 API 了,如下图示例代码: this.$common.Init.call(this); this.wxjssdkInti().then(rr =>…

课程表美化 css_通过这门11小时的免费课程学习HTML和CSS
课程表美化 cssHTML and CSS are essential skills to have for a career in web development. This eleven hour course from John Smilga of Coding Addict will teach HTML and CSS from the scratch. By the end of this course you will be creating your own projects.HT…

JavaScript创建对象的两种方法和遍历对象的属性
创建新对象有两种不同的方法: 定义并创建对象的实例使用函数来定义对象,然后创建新的对象实例1.定义并创建对象的实例 var personnew Object(); person.firstname"John"; person.lastname"Doe"; person.age50; person.eyecolor"…

微信公众号H5订阅消息开发 uniapp订阅消息
简单说一下流程: 在页面带参数跳转到 https://mp.weixin.qq.com/mp/subscribemsg ,然后用户授权确认或者取消以后,会返回参数里面 redirect_url 的地址,并且带上openid 等相应参数,在前端的页面判断链接里面携带了相关…

GRUB密码设置
通过编辑GRUB启动参数可以轻松的进入单用户模式从而修改root密码,GRUB的密码设置可分为全局密码和菜单密码。 一,全局密码设置 在splashimage这个参数的下一行可以加上password密码,保存后重新启动计算机,再次登录到GRUB菜单页…