Reputation: 1966
Is there a way to push a list of functions into an associative array? Here's what I'm trying to do:
var inits = {
"first" : fn1(),
"second" : fn2(),
"third" : fn3(),
"fourth" : fn4()
};
var functions = ['first','fourth'];
for(var index in functions ) {
inits[functions[index]];
}
The important part here is to be able to name each function and have it called based on a given array of function names. I can do this in PHP but can't figure it out how to do it in javascript.
Upvotes: 0
Views: 110
Reputation: 14282
Just a few small changes should make it work:
var inits = {
"first" : function() { /* make sure there's a function body */ },
"second" : fn2, // or this, if you intend to call a function named `fn2`
// or assigned to a locally accessible fn2 variable.
"third" : fn3(), // or this, if fn3() returns a function ...
"fourth" : fn4(), // but, this version *probably* isn't what you want.
};
var functions = ['first','fourth'];
// generally speaking, don't use for-in on an array.
for(var i = 0; i < functions.length; i++) {
// use parentheses to invoke the function
inits[functions[i]]();
}
Upvotes: 1
Reputation: 239270
First, you're not actually storing functions. You're storing the return value of functions.
To store the function, you'd use
var inits = {
'first': fn1,
'second': fn2,
...
};
Secondly, you're iterating incorrectly over the array.
Use forEach
:
functions = ['first', 'fourth'];
functions.forEach(function (fn) {
inits[fn];
});
Thirdly, in your loop, you don't actually try to invoke the function. If that's your intent, you're missing a ()
:
functions.forEach(function (fn) {
inits[fn]();
});
Upvotes: 2