【问题标题】:javascript: passing the key from for loop to another function failsjavascript:将密钥从 for 循环传递到另一个函数失败
【发布时间】:2013-09-04 06:58:50
【问题描述】:

我正在尝试将键从 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  
}

它显示的错误是: 未捕获的类型错误:无法读取等处未定义的属性“anotherProperty”

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

【问题讨论】:

    标签: javascript loops object arguments key


    【解决方案1】:

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

    试试console(anotherObject);

    可能你的对象有点不正确

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多