數組、對象數組轉化成JSON對象的情況

1、數組轉化成JSON對象後,key值是索引,value是數組對應的值。

    //數組也可以轉化成JSON對象
    var jStr3 = "[[10,20,30],40,50,60]";
    var j3 = JSON.parse(jStr3);

    for(let key in j3){
        console.log('key:',key);
    }
//    key: 0
//    key: 1
//    key: 2
//    key: 3

    for(let value of j3){
        console.log('value:',value);
    }
//    value: (3) [10, 20, 30]
//    value: 40
//    value: 50
//    value: 60

    j3.forEach((item,index)=>{
        console.log('item:',item,'index:',index);
    })
//    item: (3) [10, 20, 30] index: 0
//    item: 40 index: 1
//    item: 50 index: 2
//    item: 60 index: 3

    j3 = JSON.parse(jStr3,(key,value)=>{
        console.log('key:',key,'value:',value);
    });
// 把所有值都遍歷出來了
//    key: 0 value: 10
//    key: 1 value: 20
//    key: 2 value: 30
//    key: 0 value: (3) [empty × 3]
//    key: 1 value: 40
//    key: 2 value: 50
//    key: 3 value: 60
//    key:  value: (4) [empty × 4]

2、數組對象可以直接序列化成字符串

var jStr31 = [[10,20,30],40,50,60];
    console.log(JSON.stringify(jStr31));
    console.log(jStr31.toString());
    console.log(jStr31.join('-'));
//    [[10,20,30],40,50,60]
//    10,20,30,40,50,60
//    10,20,30-40-50-60

3、對象數組轉化成JSON對象

var jStr = '[{"name":"a"},{"name":"b"}]';
var j = JSON.parse(jStr);
console.log(j);
//    (2) [{…}, {…}]
//    0: {name: "a"}
//    1: {name: "b"}
//    length: 2
//    __proto__: Array(0)

for(let key in j){
   console.log('key:',key)
}
//    key: 0
//    key: 1


for(let item of j){
    console.log('item of:',item.name);
}
//    item of: {name: "a"}
//    item of: {name: "b"}


j.forEach((item,index)=>{
     console.log('index:',index,'item:',item);
    })
//    index: 0 item: {name: "a"}
//    index: 1 item: {name: "b"}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章