Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I store JavaScript functions in arrays?

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.

like image 466
Emre Avatar asked Aug 28 '10 21:08

Emre


People also ask

Can you call a function in an array?

It is important to remember that when an array is used as a function argument, its address is passed to a function. This means that the code inside the function will be operating on, and potentially altering, the actual content of the array used to call the function.

Can I put functions in an array C?

In this tutorial, you'll learn to pass arrays (both one-dimensional and multidimensional arrays) to a function in C programming with the help of examples. In C programming, you can pass an entire array to functions.

Can arrays store objects JavaScript?

With an array, you store a collection of elements you can access by their position (or index). Objects take that concept further by providing a way to structure related data that's easy to read and retrieve using key/value pairs. It's common to combine the two by creating an array of objects.

How do I run a function inside an array?

Typically, when you want to execute a function on every element of an array, you use a for loop statement. JavaScript Array provides the forEach() method that allows you to run a function on every element. The forEach() method iterates over elements in an array and executes a predefined function once per element.


1 Answers

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"](); 
like image 179
Anurag Avatar answered Sep 26 '22 03:09

Anurag