迭代并调用类似数组的对象内的方法

时间:2015-10-14 10:46:44

标签: javascript

我已经拥有了这个对象结构,并希望迭代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();
}

如何实现想要的行为?

3 个答案:

答案 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