javascript:将 key 从 for 循环传递到另一个函数失败

标签 javascript loops object arguments key

我试图将 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”等

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

最佳答案

检查我的 fiddle ,一切正常 Fiddle

尝试console(anotherObject);

可能你的对象有点不正确

关于javascript:将 key 从 for 循环传递到另一个函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551671/

相关文章:

javascript - 设置显示:none if element contains no text

javascript - 如何在 jQuery 中对文本产生闪光效果?

python - 我可以通过使用循环使迭代变得更容易吗?

java - HashMap ClassCastException 字符串到 MyClass

cocoa - 如何将新数组设置为 myController.arrangedObjects?

json - 将 json 对象合并为一个

javascript - ng2-charts\ng2-charts.js 不导出 ChartsModule

Javascript合并属于对象中不同键的数组值

php - 在wordpress中获取帖子的作者ID

java - 使用基于对象的 run() 方法而不是静态 main 有什么优势吗?