如何在JavaScript中访问数组内对象的值?

时间:2015-10-23 07:39:37

标签: javascript arrays object foreach

这是我的代码。

var a = [   
    {
        name:"john",
        age:18,
        interests:[
            {
                uname: "computer",
                http: "google.com"
            },
            {
                lname:"foo",
                http: "twitter.com"
            }
        ]
    },
    {
        name:"jack",
        age:21,
        interests:["movies","music"]
    }
]

a.forEach(function(obj){
    for(var key in obj) {
        console.log(key)    
    }
})

如何使用foreach循环从上面的代码中访问“uname”(“computer”)的值?

1 个答案:

答案 0 :(得分:1)

像这样:

a.forEach(function(obj){
    for(var key in obj) {
        if (key == 'interests') {
            console.log(obj[key][0].uname);
        }
    }
})