对象遍历:for…in循环(隐式迭代)
遍历:一个一个的查看
for in的语法: for (var 变量 in 要遍历的对象) { }
根据对象的键值对来循环,对象里有多少个键值对for就会循环多少次每一次循环得到的key就是当前键(属性名或者方法名)。
效果:
代码:
<script>
var ic = {
"comments": {
"lst": [{
"imageId": 123,
"content": "操作简单方便",
"creationTime": "2022-11-01 18:50:40",
"nickname": "m***9",
"productColor": "5050tt",
"userLevelName": "会员",
"userClientShow": "来自淘宝Android客户端",
},
{
"imageId": 321,
"content": "还不错,很喜欢",
"creationTime": "2023-10-05 00:51:40",
"nickname": "h***2",
"productColor": "C550tt",
"userLevelName": "会员",
"userClientShow": "来自淘宝iPhone客户端",
}
]
}
}
var ict = ic.comments.lst;
document.write("<ul>");
for (var p in ict) {
document.write(
`<li style="border:1px solid;margin-top:10px">订单编号:${ict[p].imageId}用户昵称:${ict[p].nickname}评论内容:${ict[p].content} 评论时间:${ict[p].creationTime} 会员等级:${ict[p].userLevelName} 来源:${ict[p].userClientShow} </li>`
);
}
document.write("</ul>");
</script>
例2:
效果图:
代码:
<script>
var leibie={
"一代枭雄": [
{ "name":"霍去病","age":"40"},
{ "name":"秦始皇","age":"42"},
],
"文人墨客": [
{ "name":"鲁迅","age":"40"},
{ "name":"莫言","age":"41"},
]
}
var mail=leibie.一代枭雄;
var moke=leibie.文人墨客;
document.write("一代枭雄:<br>")
for (var p in mail) {
document.write(
`姓名--->${mail[p].name} 年龄--->${mail[p].age}<br>`
);
}
document.write("文人墨客:<br>")
for (var p in moke) {
document.write(
`姓名--->${moke[p].name} 年龄--->${moke[p].age}<br>`
);
}
</script>
例3:
效果图:
代码:
<script>
var user = {
"employees": [{
"name": "安娜贝尔",
"QQ": 306451129,
"email": "安娜贝尔@163.com",
"address": [{
"City": "美国",
"ZipCode": "40000"
},
{
"City": "法国",
"ZipCode": "10000"
}
]
},
{
"name": "唐僧",
"QQ": 254892313,
"email": "唐僧@163.com",
"address": [{
"City": "大唐",
"ZipCode": "20000"
},
{
"City": "中国",
"ZipCode": "50000"
}
]
}
]
}
document.write("<ul style='color:green'>");
for (var p in user.employees) {
document.write(
`<li>名字:${user.employees[p].name}<br>QQ:${user.employees[p].QQ}<br>邮箱:${user.employees[p].email}<br></li>`
);
for (var b in user.employees[p].address) {
document.write(
`--城市:${user.employees[p].address[b].City}<br>--邮编:${user.employees[p].address[b].ZipCode}<br>`
);
}
}
document.write("</ul>");
</script>