复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*do-wile 后测试循环语句,即只有在循环体中的代码被执行后,才会测试出口条件
*
* 在对表达式求值之前,循环体内的代码至少会被执行一次
*
* 常用语循环体中的代码至少被执行一次的情形
* */
let i=0;
do{
i+=2;
}while(i<10)
console.log(i);
/*
while 前测试语句,在循环体内的代码被执行前,就会对出口条件求值
因此,循环体内的代码可能不会被执行
*
* */
let b =0;
while (b<10){
b+=2;
}
console.log(b);
/*
for 前测试循环语句(初始化表达式;控制表达式;循环后表达式)
具有 在执行循环之前初始化 变量 定义循环后要执行的代码 的能力
1.(初始化表达式;控制表达式;循环后表达式)都是可选的,都省略后会创建一个无限循环
for( ; ; ){
//做一些事
}
2.只给出控制表达式 就把for循环转换成了while循环
var i=0;
for( ;i<10; ){
i++
}
* */
/*
for-in
一种精准的迭代语句,用来枚举对象的属性
* */
/*
每次循环,都会将window对象中存在的一个属性名赋值给a,
一直持续到对象中多有的属性都被枚举一遍为止
ECMAscript对象中的属性是没有顺序的,因此for-in循环输出的属性名是不可预测的
* */
for (var a in window) {
document.write(a+'! '+'n');
}
/*
label 用于在代码中添加标签,以便将来使用
标签可以在将来由break,continue语句引用。
加标签的语句一般要与for循环语句配合使用
* */
start:for(var c=0;c<10;c++){
console.log(c);
}
/*
都用于在循环中精确得控制代码的执行
break
立即退出循环,强制继续执行后面的语句。
continue
立即退出循环,从循环的顶部继续执行
* */
var num =0;
for(var d=1;d<10;d++){
if(d%5==0){
break;
}
num++;
}
console.log("----------break---")
console.log(num);//4
var num1 =0;
for(var e=1;e<10;e++){
if(e%5==0){
continue;
}
num1++;
}
console.log("----------continue---")
console.log(num1);//8
/*
switch
为了避免开发人员像下面一样写代码
* */
var f=25;
if(f ==25){
console.log("25");
}else if(f==35){
console.log("35");
}else if(f==45){
console.log("45");
}
console.log("----以上语句用switch替换可提高性能-------")
switch (f){
case 25:
//console.log("25");
//break; //省略break 用于混合多种情形
case 35:
console.log("25||35");
break;
case 45:
console.log("45");
break;
default:
console.log("others");
break;
}
/*
switch 中可使用,任何数据类型 字符串,对象,常亮,变量,表达式.....
* */
console.log("switch 字符串---------")
let str1 = "hello world";
switch (str1){
case "hello world":
console.log("hello world");
break;
case "bye huhao":
console.log("byebye");
break;
default:
console.log("others String");
break;
}
console.log("switch bool---------")
/*
switch在比较值时使用全等操作符,因此不会发生类型转换
"10" 不等于10
* */
let h = 25;
switch (true){
case h<0:
console.log("小于0");
break;
case h>10&&h<=20:
console.log(">10");
break;
default:
console.log("超过20");
break;
}
最后
以上就是彪壮彩虹最近收集整理的关于JavaScript-for循环语句,if语句,switch语句的全部内容,更多相关JavaScript-for循环语句内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复