相信大家都使用过javascript中的for循环,主要用来遍历数组对象,方便执行重复操作,体现代码的重用性。但是,应为数组的索引一般是整 型的数字,当遇到JSON对象或者object对象时,就不能使用for循环遍历了,应当使用for in函数遍历对象,这里就谈谈个人对for in的理解。
首先,虽然叫For in语法但关键字还是用for,这个语法还可以用来遍历对象,拿到的是对象的属性名称,然后通过对象名[属性名称]就可以拿到对象。个人觉得,理解这个语法的本质,关键在于理解每次循环得到的到底是什么。
for in功能的实现得益于javascript的数组索引可以是字符串,是从for循环扩展开来的。下面举个例子,
<html>
<head>
<title></title>
<meta content="text/html" charset="utf-8"/>
<style>
input[type="button"]{
width: 100px;
height: 40px;
background-color: #f5deb3;
border-radius: 11px;
outline: 0px;
color: #ff2692;
font-size: 16px;
font-weight: bold;
}
#content{
width: 400px;
height: 400px;
margin-top: 10px;
color: #4169e1;
font-size: 20px;
font-weight: bold;
}
</style>
</head>
<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>
<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(){
this.name;
this.age;
}
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>
</html>
点击按钮one后:
0: blue
1: red
2: yellow。
点击按钮two后:
uname: 张三
age: 18
age: 18
这就是上面代码输出的结果,还可以试想,如果u1中有一个方法
u1.say=function(){
alert("hello");
},那么点击two后,就应该输出
alert("hello");
},那么点击two后,就应该输出
uname: 张三
age: 18
say: function(){ alert("hello"); }
age: 18
say: function(){ alert("hello"); }
所以,使用for in可以遍历json对象和obj对象!纯属个人心得,不对的地方,请多多指教!