<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Json</title>
</head>
<body>
<p id="exp1"></p>
<p id="exp2"></p>
<table>
<tr>
<td id="exp3"></td>
<td id="exp4"></td>
</tr>
</table>
<p id="exp5"></p>
<p id="exp6"></p>
<p id="exp7"></p>
<p id="exp8"></p>
<script>
//访问对象值(.和[]的使用)
var myObj1 = { "name":"张三", "sex":"男", "age":20 };
var x = myObj1.name;
var y = myObj1["name"];
document.getElementById("exp1").innerHTML = x;
document.getElementById("exp2").innerHTML = y;
//循环对象(for-in循环)
for (x in myObj1) {
document.getElementById("exp3").innerHTML += x + "<br>";
}
for (x in myObj1) {
document.getElementById("exp4").innerHTML += myObj1[x] + "<br>";
//在使用for遍历时,只能通过 myObj[x] 来获取相应属性的值,而不能使用 myObj.x
}
//嵌套 JSON 对象(friend嵌套在myObj2中)
var myObj2 = {
"name":"李四",
"sex":"男",
"friend": {
"name1":"张三",
"name2":"王五",
"name3":"马六"
}
}
//两种方法均可结合访问,共四种,如下
var a=myObj2.friend.name1;
var b=myObj2.friend["name1"];
var c=myObj2["friend"].name1;
var d=myObj2["friend"]["name1"];
document.getElementById("exp5").innerHTML = a;//a,b,c,d均可
myObj2.friend.name1="王麻子" //修改值(直接修改即可)
delete myObj2.friend["name2"]; //删除( delete 关键字)
//JSON 数组(在[]中书写,可通过数组下标访问)
var myObj3 = {
"name":"王五",
"sex":"男",
"friend":[ "熊大", "熊二", "翠花" ]
}
var m = myObj3.friend[0];
document.getElementById("exp6").innerHTML = m;
//循环数组(for循环)
var x="";
for (i = 0; i < myObj3.friend.length; i++) {
x += myObj3.friend[i] + "<br>";
}
document.getElementById("exp7").innerHTML = x;
//嵌套 JSON 对象中的数组
myObj4 = {
"name":"阿狸",
"sex":"女",
"friend": [
{ "name":"亚索", "skills":[ "斩钢闪", "风之障壁", "踏前斩","狂风绝息斩"] },
{ "name":"洛", "skills":[ "微光飞翎", "盛大登场", "轻舞成双","惊鸿过隙"] },
{ "name":"霞", "skills":[ "双刃", "致死羽衣", "倒钩","暴风羽刃"] }
]
}
//双层循环访问
for (i in myObj4.friend) {
x += "<h1>" + myObj4.friend[i].name + "</h1>";
for (j in myObj4.friend[i].skills) {
x += myObj4.friend[i].skills[j] + "<br>";
}
}
document.getElementById("exp8").innerHTML = x;
</script>
</body>
</html>