1

我正在尝试将 for 循环中的密钥传递给另一个函数并从那里的对象获取数据。出于某种原因,当我传递密钥时,它告诉我它是未定义的。

//this is the for loop from where I call anotherFunction
for (var key in object) { // note that this is not an array but an object 
    if (object.hasOwnProperty(key)) {               
        console.log("test :"+ anotherObject[key]["anotherProperty"]); //this works
        anotherFunction(key);               
    }
}

function anotherFunction(arg){ 
    console.log("arg: "+arg); //shows the correct argument
    console.log("test2: "+anotherObject["myProperty"]["anotherProperty"]); //this works, in other words, if I manually type the correct property it works but I want to be able to use the passed along argument
    console.log("test3: "+anotherObject[arg]["anotherProperty"]); //this doesn't work
    var arg2 = '"'+arg+'"'; //I tried adding quote characters       
    console.log("test4: "+anotherObject[arg2]["anotherProperty"]); //this doesn't work  
}

它显示的错误是: Uncaught TypeError: Cannot read property 'anotherProperty' of undefined at etc

知道为什么它不起作用以及如何使它起作用吗?

4

1 回答 1

0

检查我的小提琴,一切 正常

尝试console(anotherObject);

可能你的对象有点不正确

于 2013-08-31T19:42:11.230 回答