JSON数组类似于JavaScript数组。
JSON对象中数组的语法:
// JSON Arrays Syntax
{
"name":"Peter parker", "heroName": "Spiderman", "friends" : ["Deadpool", "Hulk", "Wolverine"]
}
访问数组值:
可以使用数组中每个元素的索引来访问数组值。
<!DOCTYPE html>
< html >
< head >
< title >Page Title</ title >
</ head >
< body >
< p id = "paraId" ></ p >
< script >
var spidermanDetail = {
"name": "Peter parker", "heroName": "Spiderman", "friends": ["Deadpool", "Hulk", "Wolverine"]
};
var x = spidermanDetail.friends[0];
document.getElementById("paraId").innerHTML = x;
</ script >
</ body >
</ html >
输出如下:
Deadpool
遍历数组:
for-in循环可用于遍历Array。
<!DOCTYPE html>
< html >
< head >
< title >Page Title</ title >
</ head >
< body >
< p id = "paraId" ></ p >
< script >
var str = "";
var spidermanDetail = {
"name": "Peter parker", "heroName": "Spiderman", "friends": ["Deadpool", "Hulk", "Wolverine"]
};
for (i in spidermanDetail.friends) {
str += spidermanDetail.friends[i] + "< br />";
}
document.getElementById("paraId").innerHTML = str;
</ script >
</ body >
</ html >
输出如下:
Deadpool
Hulk
Wolverine
修改数组值:
索引号可用于值的修改。
<!DOCTYPE html>
< html >
< head >
< title >Page Title</ title >
</ head >
< body >
< p id = "paraId" ></ p >
< script >
var str = "";
var spidermanDetail = {
"name": "Peter parker", "heroName": "Spiderman", "friends": ["Deadpool", "Hulk", "Wolverine"]
};
spidermanDetail.friends[1] = "Iron Man";
for (i in spidermanDetail.friends) {
str += spidermanDetail.friends[i] + "< br />";
}
document.getElementById("paraId").innerHTML = str;
</ script >
</ body >
</ html >
输出如下:
Deadpool
Iron Man
Wolverine
删除数组值:
可以使用delete关键字删除Array的值。
<!DOCTYPE html>
< html >
< head >
< title >Page Title</ title >
</ head >
< body >
< p id = "paraId" ></ p >
< script >
var str = "";
var spidermanDetail = {
"name": "Peter parker", "heroName": "Spiderman", "friends": ["Deadpool", "Hulk", "Wolverine"]
};
delete spidermanDetail.friends[2];
for (i in spidermanDetail.friends) {
str += spidermanDetail.friends[i] + "< br />";
}
document.getElementById("paraId").innerHTML = str;
</ script >
</ body >
</ html >
输出如下:
Deadpool
Hulk
JSON对象中的嵌套数组:
在嵌套数组中, 另一个数组也可以是一个数组的值。
<!DOCTYPE html>
< html >
< head >
< title >Page Title</ title >
</ head >
< body >
< p id = "paraId" ></ p >
< script >
var str = "";
var spidermanDetail = {
"name": "Peter parker", "heroName": "Spiderman", "friends": [{
"heroName": "Deadpool", "skills": ["Martial artist", "Assassin"]
}, {
"heroName": "Hulk", "skills": ["Superhuman Speed", "Superhuman Strength"]
}, {
"heroName": "Wolverine", "skills": ["Retractable bone claws", "Superhuman senses"]
}]
};
for (i in spidermanDetail.friends) {
str += "< h3 >" + spidermanDetail.friends[i].heroName + "</ h3 >";
for (j in spidermanDetail.friends[i].skills) {
str += spidermanDetail.friends[i].skills[j] + "< br />";
}
}
document.getElementById("paraId").innerHTML = str;
</ script >
</ body >
</ html >
输出如下: