1

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.

2
  • 1
    functions is an object, not an array. Commented Mar 6, 2015 at 1:44
  • 1
    functions is an object, not an array Commented Mar 6, 2015 at 1:44

1 Answer 1

5

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/

Sign up to request clarification or add additional context in comments.

2 Comments

OP said, he/she does not want to call it by function name.
OP also said that an object literal is an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.