ᔕᖺᘎᕊ
ᔕᖺᘎᕊ

Reputation: 3011

Execute functions whose names are in an array

I've seen How to execute a JavaScript function when I have its name as a string, Calling a JavaScript function named in a variable, Can I use the value of a variable to initiate a function?, but I can't figure out how to get this working with an array and a for loop.

What I've tried:

I have a few functions, let's say:

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

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

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

and an array:

callThese = ['one', 'two']

and I want to call one and two.

This doesn't work:

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

The error I get is TypeError: object is not a function. The functions are definitely there, and they work by calling them manually (ie. one(), two(), etc...).

Sorry if this is a basic mistake, but how do I get this working?? I don't mind a jQuery solution if there is one.

Upvotes: 0

Views: 560

Answers (2)

charlietfl
charlietfl

Reputation: 171669

You can create an object that contains the functions

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

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

Upvotes: 1

Michał Szepielak
Michał Szepielak

Reputation: 284

You need to assign functions to your object. It's not recommended to create global functions (other scripts/frameworks can overwrite them).

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]]();
}

Upvotes: 4

Related Questions