访问Javascript对象的属性失败

时间:2014-01-12 04:32:39

标签: javascript

我有一个需要将object作为参数的JS函数。我想获取对象的属性和值。以下是我的程序中的JS对象列表:

var a =[{'Jan':1555},{'Feb':456},{'Mar':987},{'Apr':768}];

正如预期的那样获取属性和值,可以在这里使用循环,如下所示:

for(var i=0;i<a.length;i++){
for(var j in a[i]){
    console.log(j);        // Here it returns the property correctly
    console.log(a[i].j);  //Returns Error here ie returns undefined
     }
}

现在上面的行 console.log(a [i] .j)会返回未定义的值,而如果手动检查列表,如 a [0]。 1555 a [1] .Feb 返回 456 ,依此类推。 为什么会这样?如果我错了,请更正代码,因为我是JS的新手。

2 个答案:

答案 0 :(得分:1)

您必须使用console.log(a[i][j]);

访问它

使用a[i].j访问它就像使用a[i]["j"]访问它一样,这不是您想要的。此外,无论何时使用for ... in,都应始终使用obj.hasOwnProperty

进行检查

请改用此代码

for(var i=0;i<a.length;i++){
    for(var j in a[i]){
        if(a[i].hasOwnProperty(j){
            console.log(j);        // Here it returns the property correctly
            console.log(a[i][j]);  
        }
     }
}

答案 1 :(得分:1)

.j属性不存在,您应该这样做:

for(var i=0;i<a.length;i++){
    for(var j in a[i]){
        console.log(j);        // Here it returns the property correctly
        console.log(a[i][j]);  //Now works
     }
}

但是,我会把它写成以下内容以使其更容易理解:

for(var i=0; i < a.length; i++){
    var item = a[i];
    for(var month in item){
        console.log("month: ", month);        
        console.log("value: ", item[month]);
     }
}

干杯

相关问题