一、对象
循环对象
使用for-in循环对象的属性,使用中括号([])访问属性值
如: var myObj = { "name":"runoob", "alexa":10000, "site":null
};
for (x in myObj) { document.getElementById("demo").innerHTML += myObj[x] + "<br>";
}
嵌套对象
如:
myObj = {
"name":"json你好",
"alexa":10000,
"sites": {
"site1":"www.baidu.com",
"site2":"m.baidu.com",
"site3":"c.baidu.com"
}
}
同样使用"."或者([])来访问嵌套对象
x = myObj.sites.site1;或者x = myObj.sites["site1"];
修改值
myObj.sites.site1 = "www.google.com";或者myObj.sites["site1"] = "www.google.com";
删除对象属性
使用delete关键字删除或者中括号([])来删除对象的属性
如:delete myObj.sites.site1;
二、数组(与对象基本一致)
对象属性的值可以是一个数组
{
"name":"网站",
"num":3,
"sites":[ "Google", "Runoob", "Taobao" ]
}
循环数组
for (i in myObj.sites) {
x += myObj.sites[i] + "<br>";
}
嵌套JSON对象中的数组
myObj = {
"name":"网站",
"num":3,
"sites": [
{ "name":"Google", "info":[ "Android", "Google 搜索", "Google 翻译" ] },
{ "name":"json", "info":[ "语法", "数组", "对象"},
{ "name":"Taobao", "info":[ "淘宝", "拼多多" ] }
]
}
修改数组元素
使用索引值来修改数组
myObj.sites[1] = "Github";
删除数组元素
使用索引值来删除数组
delete myObj.sites[1];