Home  >  Article  >  Web Front-end  >  Detailed explanation of javascript flow control statement Switch statement and for loop example code

Detailed explanation of javascript flow control statement Switch statement and for loop example code

伊谢尔伦
伊谢尔伦Original
2017-07-24 09:42:562490browse

Multiple choices (Switch statement)

When there are many options, switch is more convenient to use than if else.


 switch(表达式)
 {
 case值1:
 执行代码块 1
 break;
 case值2:
 执行代码块 2
 break;
 ...
 case值n:
 执行代码块 n
 break;
 default:
 与 case值1 、 case值2...case值n 不同时执行的代码
 }

Syntax description:
Switch must be assigned an initial value, and the value matches each case value. Satisfies all statements after executing the case, and uses the break statement to prevent the next case from running. If all case values ​​do not match, the statement after default is executed.
Example: Let’s make a weekly plan, learn concept knowledge on Monday and Tuesday, practice in the company on Wednesday and Thursday, summarize experience on Friday, rest and have fun on Saturday and Sunday.


 <script type="text/JavaScript">
   var myweek =3;//myweek表示星期几变量
   switch(myweek){
     case 1:
     case 2:
     document.write("学习理念知识");
     break;
     case 3:
     case 4:
     document.write("到企业实践");
     break;
     case 5:
     document.write("总结经验");
     break;
     default:
     document.write("周六、日休息和娱乐");
   }
 </script>

for loop
Many things are not just done once, but done repeatedly. For example, print 10 copies of the test paper, one at a time, and repeat this action until the printing is completed. We use loop statements to accomplish these things. A loop statement is to repeatedly execute a piece of code.
for statement structure:


 for(初始化变量;循环条件;循环迭代)
 { 
   循环语句 
 }

Example: If there are 6 balls in a box, we take one at a time and repeatedly take out the balls from the box until the ball While supplies last.


 <script type="text/javascript">
   var num=1;
   for (num=1;num<=6;num++){ //初始化值;循环条件;循环后条件值更新
     document.write("取出第"+num+"个球<br />");
   }
 </script>

We have 1, 2, 3...10 money of different denominations. Use the for statement to complete the total and see how much money we have in total?


 <script type="text/JavaScript">
   var mymoney,sum=0;//mymoney变量存放不同面值,sum总计
   for(mymoney=1;mymoney<=10;mymoney++){ 
     sum= sum + mymoney;
   }
   document.write("sum合计:"+sum);
 </script>

The above is the detailed content of Detailed explanation of javascript flow control statement Switch statement and for loop example code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn