执行名称在数组中的函数

时间:2015-01-10 17:01:41

标签: javascript jquery arrays

我已经看过How to execute a JavaScript function when I have its name as a stringCalling a JavaScript function named in a variableCan I use the value of a variable to initiate a function?,但我无法弄清楚如何使用数组和for循环。< / p>

我尝试过的事情:

我有一些功能,让我们说:

function one() { 
    alert('one');
}

function two() {
    alert('two');
}

function three() {
    alert('three');
}

和一个数组:

callThese = ['one', 'two']

我想致电onetwo

这不起作用:

for (i = 0; i < callThese.length; ++i) {
    //console.log(callThese[i]); <--- (outputs one and two)
    window[callThese[i]]();
}

我得到的错误是TypeError: object is not a function。这些功能肯定存在,它们通过手动调用它们来工作(即one()two()等......)。

很抱歉,如果这是一个基本错误,但我如何让这个工作?如果有jQuery解决方案,我不介意。

2 个答案:

答案 0 :(得分:4)

您需要为对象分配函数。不建议创建全局函数(其他脚本/框架可以覆盖它们)。

var obj = {
        one: function () {
            alert('one');
        },
        two: function () {
            alert('two');
        },
        three: function () {
            alert('three');
        }
    },
    callThese = ['one', 'two'];

for (var i = 0; i < callThese.length; ++i) {
    obj[callThese[i]]();
}

答案 1 :(得分:1)

您可以创建包含函数

的对象
var myFuncs = {
    one: function () {
        alert('one');
    },
    two: function () {
        alert('two');
    }
}

for (i = 0; i < callThese.length; ++i) {        
    myFuncs[callThese[i]]();
}
相关问题