How can I store functions in an array with named properties, so I can call like
FunctionArray["DoThis"]
or even
Function
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
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"]();
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!