流程控制
分支结构
if-else结构
if
语法:
if (condition){
//当条件为 true 时执行的代码
}
if…else
语法:
if (condition){
当条件为 true 时执行的代码
}else{
当条件不为 true 时执行的代码
}
if…else-if…else
语法:
if (condition1){
当条件 1 为 true 时执行的代码
}else if (condition2){
当条件 2 为 true 时执行的代码
}else{
当条件 1 和 条件 2 都不为 true 时执行的代码
}
三元运算符
三元运算符里面包含了类似if的效果
语法:condition? expression1 : expression2
当条件满足时,输出表达式1,不满足时输出表达式2
switch结构
当if…else-if…if分支太多的时候,可以用switch结构经行优化
语法:
switch(n)
{
case 1:
执行代码块 1
break;
case 2:
执行代码块 2
break;
default:
与 case 1 和 case 2 不同时执行的代码
}
附上一个例子:
var d=new Date().getDay();
switch (d)
{
case 0:x="今天是星期日";
break;
case 1:x="今天是星期一";
break;
case 2:x="今天是星期二";
break;
case 3:x="今天是星期三";
break;
case 4:x="今天是星期四";
break;
case 5:x="今天是星期五";
break;
case 6:x="今天是星期六";
break;
}
循环结构
循环结构用于一遍又一遍地运行相同的代码。
for循环
基础款for循环
遍历数组
let arr = [1,2,3];
let length = arr.length;
for(let i =0 , i<=length , i++){
console.log(arr[i]);
}
for…in循环
for…in用于遍历一个对象。但不建议用来遍历数组!!
const product = {
name:"apple",
id:233,
num:699
}
for(let i in product){
console.log(i);
console.log(product[i]);//对象可以用类似数组的方式去访问
}
for…of循环
可以用来遍历许多对象,如Array,Map,Set,String,TypedArray,arguments
var arr = [1,2,3];
for(element of arr){
console.log(element);
}
while循环
while()
语句可以在某个条件表达式为真的前提下,循环执行指定的一段代码,直到那个表达式不为真时结束循环。
let n = 0;
while (n < 3) {
n++;
}
console.log(n);
// 输出 3
do…while循环
do{
statement
}
while (condition);
do…while 不管三七二十一,先把do{}里面的语句跑一次,然后就是普通的while循环,直到condition为false就跳出循环
var result = '';
var i = 0;
do {
i += 1;
result += i + ' ';
} while (i < 5);
console.log(result);//1 2 3 4 5
可以看见,首先输出的是1而不是0,说明do{}里面的语句先执行1次。