<script> //建议使用for..in循环遍历,更简单 //效果:001 小米 10.55 var pList = [ {pid:“001”,pname:“小米”,price:“10.55”}, {pid:“007”,pname:“面条”,price:“2.10”}, {pid:“009”,pname:“大米”,price:“5.99”} ]; //外层循环:pList[i] 循环到某个商品对象 for(i in pList){ var str = “”; //内层循环:pList[i][n] 循环的是某个商品对象的某个属性 for (n in pList[i]){ str+=pList[i][n]+” “; } console.log(str); }
var classInfo = { “className”:“传智专修学院Java12班”, “stuList”:[“王五”,“赵六”,“钱七”] }; //遍历王五、赵六、钱七 var sList = classInfo[“stuList”]; for (i in sList) { console.log(sList[i]); } </script>
for(索引/属性名 in 集合){
}
数组:获取索引
json对象:获取属性名
1.4:字符串转换JSON
获取到JSON格式的字符串,该字符串无法直接作为JSON对象使用的,必须经过转换。
<script> var p1 = ‘{“name”:”刘川”,”sex”:”男”,”age”:”20″}’; console.log(p1[“name”]);//undefined //转换 var person = eval(“(“+p1+“)”); console.log(person[“name”]);//刘川 </script>