Since functions are objects in JavaScript, you can easily define their array.
function foo () { ... } function bar () { ... } function baz () { ... } var fns = [foo, bar, baz];
The signature does not matter.
From there, you can run dynamically generating functions in a loop, rather than explicitly declaring each of them:
function generator(n) { return function () { return n*n; }; } var squareFuncs = []; for (var i=0; i<10; i++) { squareFuncs.push(generator(i)); }
Then you can create arrays of arrays of functions (like any other object, remember):
function anotherGenerator(a, b) { return function () { return a+b; }; } var sumFuncs = [], temp, i, j; for (i=0; i<20; i++) { temp = []; for (j=0; j<20; j++) { temp.push(anotherGenerator(i, j)); } sumFuncs.push(temp); }
Now sumFuncs
is a two-dimensional array (actually an array of arrays) of functions that calculate the sum of the coordinates of this function in the matrix. This probably sounds more complicated than it really is, here is an example:
var foo = sumFuncs[7][2], sum = foo(); console.log(sum); // prints 9
on this topic:
source share