Reputation: 361
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
.
Upvotes: 36
Views: 82926
Reputation: 12
Storing JavaScript Functions in Arrays: Yes, You Can!
function greet(name) {
console.log(`مرحبا، ${name}!`);
}
function square(x) {
return x * x;
}
function double(x) {
return x * 2;
}
function triple(x) {
return x * 3;
}
const functionArray = [greet, square, double, triple];
functionArray[0]("صلاح");
const resultSquare = functionArray[1](4);
const resultDouble = functionArray[2](5);
const resultTriple = functionArray[3](3)
console.log(resultSquare);
console.log(resultDouble);
console.log(resultTriple);
Upvotes: 0
Reputation: 22
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
Upvotes: 1
Reputation: 139
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();
Upvotes: 2
Reputation: 61
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
Upvotes: 6
Reputation: 363
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!
Upvotes: 1
Reputation: 525
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;
Upvotes: 2
Reputation: 100331
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
Upvotes: 2
Reputation: 186562
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]()
Upvotes: 22
Reputation: 630409
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"
Upvotes: 2
Reputation: 141879
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"]();
Upvotes: 46