JavaScript语言基础 - 语句
编辑于 2021-06-03 12:27:31 阅读 1516
语句也称为流控制语句 #if语句
let i=2;
if(i>1){
console.log(111);
}
#do-while语句 do-while语句是一种后测试循环语句,循环体内的语句至少执行一次
let i=0;
do{
i+=2;
console.log(i);//2,4,6,8,10
}while(i<10);
#while语句 while语句是一种先测试循环语句
let i=0;
while(i<10){
i+=2;
console.log(i);//2,4,6,8,10
}
#for语句 for语句是一种先测试循环语句,由初始化、条件表达式、循环后表达式 3项组成
for(i=0; i<10; i++){
console.log(i);
}
//等价于
let i=0;
while(i<10){
console.log(i);
i++;
}
//初始化,条件表达式,循环后表达式,都不是必须的
for(;;){//无限循环
console.log(1);
}
let i=0;
for(; i<10;){//等价于while循环
console.log(i);
i++;
}
#for-in语句 for-in用于枚举对象中的非符号键属性(遍历key
for(const propName in window){//打印BOM对象window的所有属性
console.log(propName);
}
#for-of语句 for-of用于遍历可迭代对象的元素(遍历value
for(const i of [1,2,3,4,5]){//遍历数组中所有元素
console.log(i);//1,2,3,4,5
}
#标签语句 标签语句用于给语句加标签,应用场景是嵌套循环
start: for(const i of [1,2,3,4,5]){
console.log(i);//1,2,3,4,5
}
#break和continue语句
start: for(const i of [1,2,3,4,5]){//遍历数组中所有元素
console.log(i);//1,2,3,4,5
for(const j of [4,5,6,7,8]){
console.log(j);
if(i===3 && j===5){
break start;
}
}
}
#with语句 with语句主要用来限制代码的作用于,with语句影响性能切难于调试,一般不建议使用
with(location){
let qs=search.substring(1);
let hostName=hostname;
let url=href;
}
//等价于
let qs=location.search.substring(1);
let hostName=location.hostname;
let url=location.href;
#switch语句
let a=1;
switch(a){
case 0:
//跳过
case 1:
console.log(a);
break;
default:
console.log(11);
}