switch branch statement in JavaScript
switch branch statement
Description: Execute different codes based on different values of a variable.
Grammar structure:
switch(variable)
{
case value 1:
Code 1;
break;
case value 2:
Code 2;
break;
case value 3:
Code 3;
break;
default:
If none of the above conditions are met, execute this code;
}
switch structure description:
switch, case, break, and default are all system keywords and must be all lowercase.
The parentheses () after switch: The parentheses usually contain a variable name, and this variable may have different values.
The value of each case is compared with the value of the variable. If they are consistent, the code after the case is executed.
All cases are in an "OR" relationship, and only one case will satisfy the conditions at any time.
After the code in each case is executed, it must be ended with a break statement. After the end, the program will jump to the switch and run after the closing brace.
If you do not write a break statement, all the following case statements will be executed.
Let’s learn a system object in JavaScript, the Date object (it doesn’t matter if you don’t know the object, we will learn about it later. This section only needs to specify one of the methods)
Let’s learn from examples. It doesn’t matter if you don’t understand the object, as long as you understand the meaning
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //实例:输出今天是星期几 /* (1)创建一个日期时间对象,它中有很多的信息:时、分、秒、年、月、日、星期 (2)取出日期对象中的星期值 (3)根据星期值(0-6)来输出中文的星期几 */ //(1)创建一个系统日期时间对象,其中Date()是系统函数,首字母大写 var today = new Date(); //(2)从Date对象中取出星期值 var week = today.getDay(); //返回0-6,0代表星期日 //(3)使用switch来输出今天是星期几 var str; switch(week) { case 1: str = "一"; break; case 2: str = "二"; break; case 3: str = "三"; break; case 4: str = "四"; break; case 5: str = "五"; break; case 6: str = "六"; break; default: str = "日"; } //(4)输出结果 document.write("今天是星期"+str) </script> </head> <body> </body> </html>