这一节主要看一下循环,循环部分和java很类似,但是也有微小差距:
- while循环
- for 循环
- for in 循环
循环
while循环
while(条件语句){
循环体
}
案例循环弹出1-5
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>循环</title>
</head>
<body>
<script type="text/javascript">
var i =0;
while (i<=5){
document.write(i)
i++
}
</script>
</body>
</html>
运行结果:
012345
a++ :的含义等价——> a+=1]
for 循环
for (语句1,语句2,语句3 ){
循环体代码
}
- 语句1:在循环开始之前执行
- 语句2:循环条件(成立则执行循环体)
- 语句3:每一轮循环之后执行的语句
案例:遍历数组
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>循环</title>
</head>
<body>
<script type="text/javascript">
var arry =Array (11,"静静",'aa',8);
for(var i =0;i<arry.length;i++){
document.write(arry[i],"</br>")
}
</script>
</body>
</html>
运行结果:
11
静静
aa
8
for in 循环
for (x in arrayr){
循环体代码
}
- 遍历数组,x为数组的下标
- 遍历对象,x为对象的属性
案例:遍历数组
var arry =Array (11,"静静",'aa',8);
for(i in arry){
document.write(i)
}
运行结果:
0123
现怎么返回的不是数组元素而是下标:
for(i in arry){
document.write(arry[i],"</br>")
}
运行结果:
11
静静
aa
8
遍历对象:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>循环</title>
</head>
<body>
<script type="text/javascript">
var objC = {name: 'abc', age: 19};
// 遍历对象
for (x in objC){
document.write(x,"</br>");
alert(objC[x],"</br>")
}
</script>
</body>
</html>
发现第一个document.write(x,"</br>");
返回的是属性;就是x对应属性;
而在alert(objC[x],"</br>")
中返回value值;