0

I would like to store function pointers in an Array and then execute all of them in a foreach loop.

var array = new Array();

array['foo'] = function() { doFoo(); };
array['bar'] = function() { doBar(); };

How do I iterate and execute all functions in array?

3
  • 1
    JavaScript arrays are intended to be used with numeric indexes. Assigning to the same index twice overwrites the previous assignment. Commented Sep 13, 2014 at 18:36
  • What is the question? Commented Sep 13, 2014 at 18:37
  • Updated my question. The double iteration was not my question. Sorry for being a bit unclear. Commented Sep 13, 2014 at 18:37

1 Answer 1

1

First, if you really want to use non-numeric property names, you don't need an array:

var obj = {};

obj["foo"] = function() { doFoo(); }
obj["bar"] = function() { doBar(); }

To iterate and call the functions:

for (var k in obj) {
  obj[k]();
}

To be pedantic, it's usually considered a good idea to make sure you're not running into unexpected properties inherited from the prototype:

for (var k in obj) {
  if (obj.hasOwnProperty(l))
    obj[k]();
}
Sign up to request clarification or add additional context in comments.

Comments

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.