JavaScript中的流程控制语句总结

JavaScript语言中的流程控制语句与Java语言中几乎完全一致,分支流程可以使用if else结构或switch结构,循环流程可以使用for或while循环,具体语法如下。

1.if语句的语法结构

if语句的语法结构如下:

1.???????? if?(条件表达式A)?{
2.???????? //条件表达式A为true,所执行的代码块
3.???????? }?else?if(条件表达式)B?{
4.???????? ????//条件表达式B为true,所执行的代码块
5.???????? }?else?{
6.???????? ????//?条件表达式A和条件表达式B都为false,所执行的代码块
7.???????? }

2.switch语句的语法结构

switch语句的语法结构如下:

1.???????? switch?(表达式)?{
2.???????? ???case?值1?:
3.???????? ???????//表达式与值1匹配时,所执行的代码块
4.???????? ????????break;
5.???????? ???case?值2?:
6.???????? ???????//表达式与值2匹配时,所执行的代码块
7.???????? ????????break;
8.???????? ???default?:
9.???????? ???????//所有case值都与表达式不匹配时,所执行的代码块
10.????? }

3.for语句的语法结构

for语句的语法结构如下:

1.???????? for?(初始化语句;?循环判断条件;?循环执行语句)?{
2.???????? ???????//循环体
3.???????? }

4.while语句的语法结构

while语句的语法结构如下:

1.???????? while?(循环判断条件)?{
2.???????? //循环体
3.???????? }

5.do…while语句的语法结构

do…while语句的语法结构如下:

1.???????? do?{
2.???????? //循环体
3.???????? }?while?(循环判断条件);

6.综合演示

下例综合使用各种流程结构通过javascript动态在页面中生成一个隔行换色的HTML表格,其中用到了document.write()方法,该方法用于向HTML页面中输出内容。

1.???????? <html>
2.???????? <head>
3.???????? <meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8">
4.???????? <script?type="text/javascript">
5.???????? ????//rows为表格的行数,cols为表格的列数
6.???????? ????var?rows?=?6;
7.???????? ????var?cols?=?8;
8.???????? ????document.write('<table?width="100%"?border="1">');
9.???????? ????document.write('<caption>动态生成表格</caption>');
10.????? ????document.write('<tbody>');
11.????? ????for?(var?row?=?0;?row?<?rows;?row++)?{
12.????? ????????if?(row?%?2?==?0)?{
13.????? ????????????document.write('<tr?bgcolor="#cccccc">');
14.????? ????????}?else?{
15.????? ????????????document.write('<tr>');
16.????? ????????}
17.????? ????????for?(var?col?=?0;?col?<?cols;?col++)?{
18.????? ????????????document.write('<td>'?+?col?+?'</td>');
19.????? ????????}
20.????? ????????document.write('</tr>');
21.????? ????}
22.????? ????document.write('</tbody>');
23.????? ????document.write('</table>');
24.????? </script>
25.????? </head>
26.????? <body>
27.????? </body>
28.????? </html>
Seo先生博客发布,转载请注明,本文固定链接地址:https://seosir.cc/649.html