<form id="dlljd"></form>
        <address id="dlljd"><address id="dlljd"><listing id="dlljd"></listing></address></address>

        <em id="dlljd"><form id="dlljd"></form></em>

          <address id="dlljd"></address>
            <noframes id="dlljd">

              聯系我們 - 廣告服務 - 聯系電話:
              您的當前位置: > 關注 > > 正文

              JSON數組操作方法詳解 Js中對JSON數組的常用操作

              來源:CSDN 時間:2023-02-24 11:22:06

              JSON數組操作

              我們首先定義一個json數組對象如下:

              var persons = [    {name: "tina", age: 14},    {name: "timo", age: 15},    {name: "lily", age: 16},    {name: "lucy", age: 16}]


              【資料圖】

              一. 根據對象屬性值得到相應對象

              //1. 獲取 name 等于 lily 的對象var lily = persons.filter((p) => {return p.name == "lily";});console.log(lily); //打印結果 [{name: "lily", age: 16}]//注:filter()方法返回的是一個數組var twins = persons.filter((p) => {return p.age == 16;});console.log(twins); //打印結果 [{name: "lily", age: 16},{name: "lucy", age: 16}]

              二. 刪除其中一個對象

              //刪除 name 等于 tina 的對象,利用splice()方法//1. 首先我們要得到這個對象var tina = persons.filter((p) => {return p.name == "tina";});//2. 其次得到這個對象在數組中對應的索引var index = persons.indexOf(tina[0]);//3. 如果存在則將其刪除,index > -1 代表存在index > -1 && persons.splice(index, 1);console.log(persons);//打印結果 [{name: "timo", age: 15}, {name: "lily", age: 16}, {name: "lucy", age: 16}]

              三. 修改其中一個對象的屬性值

              //將 name 等于 timo 的 age 修改為 20//1. 得到 timo 對象var timo = persons.filter((p) => {return p.name == "timo";});//2. 修改agetimo[0].age = 20;

              四. 往數組中添加一個對象

              persons.push({name: "similar", age: 18});

              五.將兩個json數組進行拼接

              var c = a.concat(b);

              JSON對象的操作

              JSON對象是無序的對象可以包含多個key/value(鍵/值)對key 必須是字符串,value 可以是合法的 JSON 數據類型(字符串, 數字, 對象, 數組, 布爾值或 null)

              訪問對象值

              可以使用點號(.)來訪問對象的值:

              var myObj, x;myObj = {"name":"runoob", "alexa":10000, "site":null };x = myObj.name;

              可以使用中括號([])來訪問對象的值:

              var myObj, x;myObj = {"name":"runoob", "alexa":10000, "site":null };x = myObj["name"];

              使用 for-in 來循環對象的屬性:

              var myObj = {"name":"runoob", "alexa":10000, "site":null };for (x in myObj) {document.getElementById("demo").innerHTML += x + "";}

              在 for-in 循環對象的屬性時,使用中括號([])來訪問屬性的值:

              var myObj = {"name":"runoob", "alexa":10000, "site":null };for (x in myObj) {document.getElementById("demo").innerHTML += myObj[x] + "";}

              責任編輯:

              標簽:

              相關推薦:

              精彩放送:

              新聞聚焦
              Top 中文字幕在线观看亚洲日韩