我已经拥有了这个对象结构,并希望迭代obj
的所有直接子对象并调用他们的myMethod
方法。
虽然for...in
正确地迭代它们但我总是会收到此错误o.myMethod is not a function
这是JSFiddle
obj = {
test1: {
"name": "test1string",
"myMethod": function(){
console.log("test 1 method called")
}
},
test2: {
"name": "test2string",
"myMethod": function(){
console.log("test 2 method called")
}
}
};
for (var o in obj) {
console.log(o.name());
o.myMethod();
}
如何实现想要的行为?
答案 0 :(得分:4)
这是因为o
循环corresponds to keys and not to values中的for
。
要使用square-bracket notation获取值:obj[o].myMethod();
。
答案 1 :(得分:2)
obj[o].myMethod()
。 for .. in
为您提供成员的名称,而不是值。
答案 2 :(得分:1)
像obj[o].name
一样使用它。这是更新的fiddle