for...in 语句: 循环遍历数组中的元素、或对象的属性

标签: for in  循环遍历  遍历数组  遍历对象属性

<html>
<body>
<script type="text/javascript">

//用于遍历数组中的元素
var x
var mycars = new Array()//等价于["宝马","奔驰","宾利"]
mycars[0] = "宝马"
mycars[1] = "奔驰"
mycars[2] = "宾利"

for (x in mycars)
{
document.write(mycars[x] + "<br />")   //结果:宝马,奔驰,宾利
}


//用于遍历对象的属性
var x
var food={
a:"apple",
b:"banana",
c:"cherry"
}

for (x in food)
{
document.write(x + "<br />")  //结果:a,b,c
}

</script>
</body>
</html>

 

 

原文链接:加载失败,请重新获取