json數(shù)組的寫法:1、使用【for-in】來訪問數(shù)組;2、使用索引值來修改數(shù)組值;3、使用delete關(guān)鍵字來刪除數(shù)組元素,代碼為【delete myObj.sites[1];】。
本文操作環(huán)境:Windows7系統(tǒng),Dell G3電腦。
json數(shù)組的寫法:
數(shù)組作為 JSON 對象
[ "Google", "Runoob", "Taobao" ]
JSON 數(shù)組在中括號中書寫。
JSON 中數(shù)組值必須是合法的 JSON 數(shù)據(jù)類型(字符串, 數(shù)字, 對象, 數(shù)組, 布爾值或 null)。
JavaScript 中,數(shù)組值可以是以上的 JSON 數(shù)據(jù)類型,也可以是 JavaScript 的表達(dá)式,包括函數(shù),日期,及 undefined。
JSON 對象中的數(shù)組
對象屬性的值可以是一個數(shù)組:
{ "name":"網(wǎng)站", "num":3, "sites":[ "Google", "Runoob", "Taobao" ] }
我們可以使用索引值來訪問數(shù)組:
x = myObj.sites[0];
循環(huán)數(shù)組
你可以使用 for-in 來訪問數(shù)組:
for (i in myObj.sites) { x += myObj.sites[i] + "<br>"; }
你也可以使用 for 循環(huán):
for (i = 0; i < myObj.sites.length; i++) { x += myObj.sites[i] + "<br>"; }
嵌套 JSON 對象中的數(shù)組
JSON 對象中數(shù)組可以包含另外一個數(shù)組,或者另外一個 JSON 對象:
myObj = { "name":"網(wǎng)站", "num":3, "sites": [ { "name":"Google", "info":[ "Android", "Google 搜索", "Google 翻譯" ] }, { "name":"Runoob", "info":[ "菜鳥教程", "菜鳥工具", "菜鳥微信" ] }, { "name":"Taobao", "info":[ "淘寶", "網(wǎng)購" ] } ] }
我們可以使用 for-in 來循環(huán)訪問每個數(shù)組:
for (i in myObj.sites) { x += "<h1>" + myObj.sites[i].name + "</h1>"; for (j in myObj.sites[i].info) { x += myObj.sites[i].info[j] + "<br>"; } }
修改數(shù)組值
你可以使用索引值來修改數(shù)組值:
myObj.sites[1] = "Github";
刪除數(shù)組元素
我們可以使用 delete 關(guān)鍵字來刪除數(shù)組元素:
delete myObj.sites[1];
相關(guān)免費學(xué)習(xí)推薦:php編程(視頻)