36

How can I store functions in an array with named properties, so I can call like

FunctionArray["DoThis"]

or even

FunctionArray[integer]

?


Note: I do not wish to use eval.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Emre
  • 361
  • 1
  • 3
  • 4
  • possible duplicate of [Javascript Array of Functions](http://stackoverflow.com/questions/4908378/javascript-array-of-functions) – sergdenisov Aug 25 '15 at 15:04

9 Answers9

46

The important thing to remember is that functions are first class objects in JavaScript. So you can pass them around as parameters, use them as object values and so on. Value(s) in an array are just one example of that.

Note that we are not storing the functions in an array although we can do that and access them with a numeric index. We are storing them in a regular object keyed by the name we want to access that function with.

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

call as

functions.blah();

or

functions["blah"]();
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • How can I call a function in that array in another function which is in the array aswell – utdev Feb 17 '17 at 14:10
21

You want an object literal, not an array.

x = { 'dothis': function() { alert('hi'); } };

Object

x['dothis']()

You can also dynamically invoke

y = 'dothis';
x[y]()

Static/hard coded invocation:

x.dothis()

If you do want an array though:

x = [function(){alert('hi');}][0]()
Trevor
  • 10,903
  • 5
  • 61
  • 84
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
6

You can actually do that. Just declare it outside the array, like so...

const your_function = function(){ console.log("I am your function") }

const group = [0, "lizard", false, your_function()]

group[3]

You may also change where it's called, if you want to...

const your_function = function(){ console.log("I am your function") }

const group = [0, "lizard", false, your_function]

group[3]()

Functions were named wrong :/ sry

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fillipe Ogg
  • 61
  • 1
  • 3
2

You even can use a function as the name of the property:

var func = function(a, b){alert(a+b)};
var obj = {};
obj[func] = 2;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dmitry Masley
  • 525
  • 4
  • 9
2

You can store things directly in an array, but as an object, for example:

var Functions = { DoThis: function() { alert("do this"); } };

Functions['DoThis'](); //alerts "do this"
Functions.DoThis()     //alerts "do this"

You can give it a try here.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    hmm .. Thanks! why this wouldn't work? var FunctionArray = []; FunctionArray["m+"] = function(){...} – Emre Aug 28 '10 at 21:14
  • 1
    hmm it worked when I say FunctionArray["whatever"](); thanks again – Emre Aug 28 '10 at 21:15
  • 1
    @Emre - That's an array, to make it work just create an object instead using `var FunctionArray = {};` as the first line :) – Nick Craver Aug 28 '10 at 21:16
  • 1
    @Emre – You *can* store functions using named references in an array, as an array is merely a (special kind of) object. The problem with the example in your first comment is that `+` is not a [valid character in an identifier](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Variables) in many JavaScript implementations. – Marcel Korpel Aug 28 '10 at 22:08
2

You can access an object's properties through its name (x["A"]). If you want to assign indexes (0 = "A") you have to do this, and here is an example. (I'm not sure if the for loop will work on any browser; I've tested on Firefox, but you can get the idea.)

var x = {};

x.A = function() { alert("func 1"); };
x.B = function() { alert("func 2"); };


var i = 0;
for (a in x)
{
    x[i] = x[a];
    ++i;
}


x[0](); // func 1
x[1](); // func 2
x["A"](); // func 1
x["B"](); // func 2
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • 1
    **Don't** expect `x[0]` being `x.A` and `x[1]` being `x.B` after that loop; `for … in` iterates over the properties of an object in [an arbitrary order](https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in#Description). But you can do something like `x[0] = x.A; x[0]();`. – Marcel Korpel Aug 28 '10 at 22:00
  • Can you reproduce it? I guess the order is not really arbitrary, it depends on the order you defined. At least I can't reproduce that. – BrunoLM Aug 28 '10 at 23:58
  • The order is not "arbitrary" in the sense that browsers' implementations tend to go in the order they were defined. But that's the browser's individual implementation decision. By spec, an object literal does not have a strict order. So although the code will likely execute without any negative artifacts in the order defined, you should not necessarily DEPEND on it, because a browser may change their implementation, or a new browser could enter the scene which does not implement this way. – Greg Pettit Jun 15 '16 at 13:43
1

Here is an array that contains various data types, including a function.

Although there is an object in this example, the function is not within the object.

If you replace this object with a string, the function will still work as planned.

I can call the function from within or without the array.

myArray = [
        1,
        true,
        "String",
        {
            name: "trey",
            age: 43,
        },
        [1,2,3,4],
        myFunction = function(){
            console.log("What\'s up!");
        },
        myArray[5](),
    ];
    console.log(myArray);
    myArray[5]();

Here is the output:

What's up!
[ 1, true, 'String', { name: 'trey', age: 43 }, [ 1, 2, 3, 4 ], [Function], undefined ]
What's up!
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Trey Brister
  • 363
  • 2
  • 5
1

Basically, a function is a special type of object in JavaScript. And in JavaScript, in array you can store anything (not necessarily of the same type). So going by this, yes!, you can store a function, object, and primitive values in an array in JavaScript:

var arr = ["Hello", true, false, 1, {name: "Arshad"}, function(){}]

And you can mix the object and function to make the named function like:

{ callBythisname: function(){ .... }}

You can store this object in an array as well:

var arr = [{ callBythisname: function(){ .... }}];

If you want to call it, call like:

arr[0].callBythisname();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arshad
  • 109
  • 2
  • 10
0

The answer is has a simple answer, but it doesn't to be simplified by the answers in this thread. The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.

Example:

let a = 1;
let b = 2;

let arr = [
  a,
  b,
  function () {
    return a + b;
   },
  ];

console.log(arr[2]()); // return 3
console.log(typeof arr); // returns object
Elugens
  • 12
  • 2