JavaScript 程序的一系列语句会按照编码顺序,自上而下依次执行。
表达式语句
声明语句
仅有声明变量和声明函数两种情况。
条件语句
1、if 语句
//if(条件表达式) 可执行语句 简写格式
if(condition) statement;
/* 全写格式
if(条件表达式){
可执行语句
}
*/
if(condition){
statement;
}
当 condition 为 true 时,执行真区间 statement 。
2、if...else 语句
//简写格式
if(condition) statement1; else statement2;
//全写格式
if(condition){
statement1;
}else{
statement2;
}
当 condition 为 true 时,执行真区间 statement1,当 condition 为 false时,执行假区间 statement2。
3、else if 语句
//简写格式
if(condition1) statement1;
else if(condition2) statement2;
...
else statementn;
//全写格式
if(condition1){
statement1;
}else if(condition2){
statement2;
}
...
else{
statementn;
}
若 if(条件表达式为真) 则执行对应大括号里的 statement 语句,当所有条件表达式都为 false 时,执行 else 对应的假区间。
4、switch 语句
switch 语句用于单个条件多种情况的判断。
switch(condition){
case value1:
statement;
break;
case value2:
statement;
break;
...
default:
statement;
}
switch 结构由关键字 case、break、default 共同组成。关键字 case 用于指定可能的情况(全等于,当数据类型与值完全相等时,case 情况才会被匹配到);关键字 break 用于通知可执行代码块的结束,跳出 switch 结构;关键字 default 可以省略,当所有 case 情况均未能匹配时,才会执行 default 对应的代码。
循环语句
1、while 循环
//简写格式
while(condition) statement;
//全写格式
while(condition){
statement;
}
//例
var num = 1;
while(num <= 20){
console.log(num);
num ++;
}
//打印结果:1~20。
如果 condition 为 true 则继续循环,为 false 时则终止循环。执行步骤:先判断 condition,再执行,为 true 进入循环,为 false 不进入循环。
2、do...while 循环
//简写格式
do
statement;
while(condition);
//全写格式
do{
statement;
...
}while(condition);
与 while 循环的区别:第一次执行时不会去判断 condition 是否为 true,第一次执行完后再去再判断 condition 是否为 true,为 true 则继续执行循环,直到为 false 时终止循环。
3、for 循环
//简写格式 for(初始化表达式,条件表达式,自增表达式) statement;
for(var i = 0;i < 20;i++) console.log(i); //打印结果:0~19
/*全写格式
for(初始化表达式,条件表达式,自增表达式){
statement;
}
*/
for(var i = 0;i < 20;i++){
console.log(i); //打印结果:0~19
}
4、for...in 循环
通常用来遍历对象和数组。
跳出语句
label、break、continue。
1、label 语句
label 语句可以给代码添加标签。可与 break 和 continue 配合使用。
2、break 语句
跳出距离最近的循环结构。若后面跟一个标签名则跳出指定标签的语句结构。
3、continue 语句
跳过本次循环。若后面跟一个标签名则跳过一次指定标签的语句结构。