javascript 數組對象與嵌套循環寫法

'use strict'

var info=[{"name":"最近想跳河","interst":["歷史","美食"],"wife":{"name":"a.wen","interst":["旅遊","美食","教育人"]}}];

// ES6寫法
for(let person of info){
    console.log(person);
    console.log("姓名:"+person.name)
    for(let interst of person.interst){
        console.log("愛好:"+interst);
    }
    console.log(person.wife);
    console.log("老婆的名字:"+person.wife.name);
    for(let interst of person.wife.interst){
        console.log("老婆的愛好:"+interst)
    }
}

// ES5寫法
for(var p=0;p<info.length;p++){
    console.log(info[p]);
    console.log("姓名:"+info[p].name)
    for(var i=0;i<info[p].interst.length;i++){
        console.log("愛好:"+info[p].interst[i]);
    }
    console.log(info[p].wife);
    console.log("老婆的名字:"+info[p].wife.name);
    for(var j=0; j<info[p].wife.interst.length;j++){
        console.log("老婆的愛好:"+info[p].wife.interst[j])
    }
}

// ES5寫法
for(var p in info){
    console.log(info[p]);
    console.log("姓名:"+info[p].name)
    for(var i in info[p].interst){
        console.log("愛好:"+info[p].interst[i]);
    }
    console.log(info[p].wife);
    console.log("老婆的名字:"+info[p].wife.name);
    for(var j in info[p].wife.interst){
        console.log("老婆的愛好:"+info[p].wife.interst[j])
    }
}

 

相關文章
相關標籤/搜索