我试图将 key 从 for 循环传递到另一个函数,并从那里的对象获取数据。由于某种原因,当我传递 key 时,它告诉我它是未定义的。
//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
}
它显示的错误是: 未捕获的类型错误:无法读取未定义的属性“anotherProperty”等
知道为什么它不起作用以及如何让它起作用吗?
最佳答案
关于javascript:将 key 从 for 循环传递到另一个函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551671/