简体   繁体   English

如何在JSON对象上使用foreach调用javascript函数?

[英]How can I call javascript function using a foreach on a JSON object?

My problem is pretty easy to understand. 我的问题很容易理解。 I have a JSON object (see code) and I will automatically call all functions of this object in the order that those appears. 我有一个JSON对象(请参见代码),我将按照出现的顺序自动调用该对象的所有功能。
.

var installer = {
    a : function() {
          ...
        }
    b : function() {
          ...
        }
};

for(var func in installer) {
    fn.call(document);
};

Have you any idea why the previous code doesn't work ? 您知道为什么以前的代码不起作用吗? I'm sorry, I'm a beginner in javascript. 抱歉,我是javascript的初学者。

Thanks in advance ! 提前致谢 !

Regards. 问候。

You don't have a variable called fn , and you are also missing commas at the end of your function definitions. 您没有名为fn的变量,并且在函数定义的末尾还缺少逗号。

Additionally, your functions will not be called in order because JavaScript orders your object properties arbitrarily. 此外,您的函数将不会按顺序调用,因为JavaScript会随意对对象属性进行排序。 You may want to consider using an array or, as I have done below, specify an array that determines the order. 您可能要考虑使用数组,或者像下面我所做的那样,指定一个确定顺序的数组。

var installer = {
    a : function() {
          ...
        },
    b : function() {
          ...
        },
};

var order = [ "a", "b" ];

for(var i = 0; i < order.length; i++) {
    installer[order[i]].call(document);
}

You declare var func as the variable to loop through the members of installer , yet you use fn.call(...) . 您将var func声明为循环遍历installer成员的变量,但是您使用了fn.call(...) Where did fn come from? fn来自哪里?

Should you be able to do: installer[func].call(document) instead of fn.call(document) . 您是否应该能够做到: installer[func].call(document)而不是fn.call(document)

Also your functions declared in the installer object don't take any arguments, yet you're passing document as an argument. 同样,在安装程序对象中声明的函数不带任何参数,但是您将document作为参数传递。

[updated code to add missing .call to installer[func](document) ] [更新的代码将缺少的.call添加到installer[func](document) ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM