gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:55:32 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com