Sunday, 15 May 2011

Pushing functions into an Array in Javascript -



Pushing functions into an Array in Javascript -

is there way force list of functions associative array? here's i'm trying do:

var inits = { "first" : fn1(), "second" : fn2(), "third" : fn3(), "fourth" : fn4() }; var functions = ['first','fourth']; for(var index in functions ) { inits[functions[index]]; }

the of import part here able name each function , have called based on given array of function names. can in php can't figure out how in javascript.

first, you're not storing functions. you're storing return value of functions.

to store function, you'd utilize

var inits = { 'first': fn1, 'second': fn2, ... };

secondly, you're iterating incorrectly on array.

use foreach:

functions = ['first', 'fourth']; functions.foreach(function (fn) { inits[fn]; });

thirdly, in loop, don't seek invoke function. if that's intent, you're missing ():

functions.foreach(function (fn) { inits[fn](); });

javascript arrays

No comments:

Post a Comment