1

I have something like this:

var functions = ['function1','function2','function3'];

How would I run a certain function?

function[0];

Ideally I would like to use a count of some sort to call a function individually. I am able to get the correct output but it does not actually execute the function.

Thanks!

NickZA
  • 181
  • 6
  • 2
    You are storing strings (function names) in your array, not functions. Are these functions defined in the global scope? Are they methods exposed by a specific object? – Frédéric Hamidi May 27 '14 at 08:05
  • Well, I changed the from function names to functions using this as an example: http://jsfiddle.net/mzxCk/. It however only appears to work in firefox and not chrome (the browser I am testing in). – NickZA May 27 '14 at 08:29
  • Your fiddle works fine for me on Chrome 35.0.1916.114 m. – Frédéric Hamidi May 27 '14 at 08:32
  • And for me. It works in firfox, i at least have something to work with. Thanks for all the help . Your time is appreciated! – NickZA May 27 '14 at 08:36

3 Answers3

2
var array_of_functions = [
    first,
    second,
    third,
    forth
]

and call like

array_of_functions[count](parameters);

example

array_of_functions[0]();

or

array_of_functions[0]('string');

JSFIDDLE DEMO: http://jsfiddle.net/mzxCk/

coder hacker
  • 4,612
  • 1
  • 22
  • 48
  • 2
    You should note that `first`, `second` etc, obviously need to be defined as functions first (e.g. `function first() { //do something }` – Akurn May 27 '14 at 08:06
  • They are defined, but still does not execute. Does the placement of the function matter? – NickZA May 27 '14 at 08:12
1

Like this:

window[functions[0]]();
               //^---------- use index here

Use bracket notation to get the function name and call it by ().

This answer assumes that you have those functions with those names in global scope.

Fiddle

Amit Joki
  • 53,955
  • 7
  • 67
  • 89
0

You also need to consider calling scope, which is why you should be using call or apply depending on whether you're passing your arguments as separate objects or an array see here for a description of both.

If your functions contains a collection of strings, you'll need to invoke them (with args) like this (note the this as the first param of call, this is the scope the function will run under, so in this case window):

var func1 = function (msg) {
  document.write("func1 called with message - " + msg + ".");
};
var functions = ['func1', 'func2'];
window[functions[0]].call(this, 'here is a message');

If functions contains a collection of Function then you need to call them like this:

var functions = [
  function (msg) {
    document.write("func1 called with message - " + msg + ".");
  },
  function (msg) {
    document.write("func2 called with message - " + msg + ".");
  }];
functions[0].call(this, 'here is a message');
Community
  • 1
  • 1
Paul Aldred-Bann
  • 5,454
  • 4
  • 31
  • 53