流程控制:分支(条件)、循环
- 分支语句
条件语句: - if 语句:只有当指定条件为true时,使用该语句来执行代码
if (condition)
{
当条件为 true 时执行的代码
}
- if-else语句:当条件为true时,执行if中代码;条件为false时,执行else中代码
if (condition)
{
当条件为 true 时执行的代码
}
else
{
当条件不为 true 时执行的代码
}
- if…else if…else 语句: 使用该语句来选择多个代码块之一来执行
if (condition1)
{
statement1
当条件 1 为 true 时执行的代码
}
else if (condition2)
{
statement2
当条件 2 为 true 时执行的代码
}
else
{
statement3
当条件 1 和 条件 2 都不为 true 时执行的代码
}
- switch 语句: 使用该语句来选择多个代码块之一来执行
switch(n)
{
case 1:
执行代码块 1
break;
case 2:
执行代码块 2
break;
default:
与 case 1 和 case 2 不同时执行的代码
}
switch语句会配合default关键词来规定匹配不存在时做的事情
- 循环语句
循环可以将代码执行指定的次数
不同类型的循环: - for :循环代码一定的次数
- for/in:循环遍历对象的属性
- while:当指定的条件为true时循环指定的代码块
- do/while:同样当指定的条件为true时循环指定的代码块