fia928
fia928

Reputation: 143

How to call index number of function array in javascript

I have the following list of functions:

var functions = {
                    blah: function () {
                        alert("blah");
                    },
                    foo: function () {
                        console.log("foo");
                    }
                };

I am now trying to access a specified index of the functions array, however I'm only getting undefined.

So console.log(functions[0]); returns undefined.

Can anyone explain why this is happening and instruct me on how to call a specified index of a function array in javascript? I need to cycle sequentially through the array, so need to call it by position number rather than name.

Upvotes: 1

Views: 3016

Answers (1)

Donal
Donal

Reputation: 32713

It is not an array. It is an object.

You simply call it like this:

functions.foo();

or

functions.blah();

If you want to have an array of functions, your syntax would look something like this:

var functions = [{
    blah: function () {
        alert("blah");
    }
}, {
    foo: function () {
        console.log("foo");
    }
}];

You would call it like this:

functions[0].blah();

You can even do this:

var functions = [alert("blah"), console.log("foo")];

functions[0];
functions[1];

See here: http://jsfiddle.net/donal/29r8sthd/1/

Upvotes: 5

Related Questions