for...in 语句用于对数组或者对象的属性进行循环操作。
for ... in 循环中的代码每执行一次,就会对数组的元素或者对象的属性进行一次操作。
语法:
for
(变量in
对象) { 在此执行代码 }
“变量”用来指定变量,指定的变量可以是数组元素,也可以是对象的属性。
<html>
<heap>
<script type="text/javascript">
var mycolors = new Array('blue','red','yellow');
function f1(){
var content="";
for(var key in mycolors){
content += key+": "+mycolors[key]+"<br/>";
}
document.getElementById("content").innerHTML = content;
}
function User(){}
function f2(){
var u1=new User();
u1.uname="张三";
u1.age="18";
var content="";
for(var key in u1){
content += key+": "+u1[key]+"<br/>";
}
document.getElementById("content").innerHTML = content;
}
</script>
</heap>
<body>
<input type="button" id="c1" name="c1" οnclick="f1();" value="click one"/>
<input type="button" id="c2" name="c2" οnclick="f2();" value="click two"/>
<div id="content"></div>
</body>
</html>
点击click one后输出:
0: blue
1: red
2: yellow
1: red
2: yellow
点击click two后输出:
uname: 张三
age: 18
age: 18
当然如果u1中有一个方法:
u1.sai=function(){
alert("hello");
}
那么点击click two后就输出:
uname: 张三
age: 18
sai: function(){ alert("hello"); }
age: 18
sai: function(){ alert("hello"); }
参考这个可遍历json对象了