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
.
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.
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.
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.
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.
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"]();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With