1.if条件语句
语句一:
if (condition) {
statement1;
} else {
statement2;
}
<script>
var i=23;
if(i>25)
console.log("Greater than 25");
else{
console.log("Less than or equal to 25");
}
</script>
语句二:
if (condition) {
statement1;
} else if (condition) {
statement2;
} else {
statement3;
}
<script>
if(i>25){
console.log("Greater than 25");
} else if(i<0){
console.log("Less than 0");
} else {
console.log("Between 0 and 25,inclusive");
}
</script>
2.do-whiler循环语句
语句:
do {
statement;
} while (expression);
在对条件表达式求值之前,循环体内的代码至少会被执行一次
<script>
var i=0;
do{
i+=2;
}while(i<10);
console.log(i);
</script>
3.while循环语句
属于前测试循环语句,在循环体内的代码被执行之前,就会对出口条件求值。因此,循环体内的代码可能永远不会被执行
语句:
while (expression) {
statement;
}
<script>
var i=0;
while(i<10){
i+=2;
}
console.log(i);
</script>
4.for循环语句
语句:
for (initialization;expression;post-loop-expression) {
statement;
}
<script>
var count=10;
for(var i=0;i<count;i++){
console.log(i);
}
</script>
5.for-in语句
可以用来枚举对象的属性
语句:
for (property in expression) {
statement;
}
<script>
for(var propName in window){
document.write(propName);
}
</script>
6.break和continue语句
- break:立即跳出循环,强制执行循环后面的语句
- continue:立即跳出本次循环进入下次循环
break:
<script>
var num=0;
for(var i=1;i<10;i++){
if(i%5==0){
break;
}
num++;
}
console.log(num);
</script>
continue:
<script>
var num=0;
for(var i=1;i<10;i++){
if(i%5==0){
continue;
}
num++;
}
console.log(num);
</script>
两者混合使用:
<script>
//1-100之间不能被3整除的整数的第一个大于2000的和
var sum=0;
for(var i=1;i<=100;i++){
if(i%3==0){
continue;
}
sum+=i;
if(sum>2000){
console.log(sum);
break;
}
}
</script>
7.switch语句
语句:
switch (expression) {
case value:
statement;
break;
case value:
statement;
break;
case value:
statement;
break;
default:
statement;
}
<script>
var num=25;
switch(true){
case num<0:
console.log("Less than 0");
break;
case num>=0&&num<=10:
console.log("Between 0 and 10");
break;
case num>10&&num<=20:
console.log("Between 10 and 20");
break;
default:
console.log("more than 20");
}
</script>