passing an argument to anon function inside array - returning output with console.log

Here is the simple codeschool javascript math problem.

I need help with iteration through array with array method - map(). How can I return (with console.log) results of every array cell? What is the best way to pass, for example, some number as parameter of anonymous function (a). Thanks for any help you can provide...

var puzzlers = [
    function (a) { return 3 * a - 8;},
    function (a) { return (a+2) * (a+2) * (a+2);},
    function (a) { return (Math.pow(a,2) - 9);},
    function (a) { return a % 4;}
];

Answers


You can do a foreach using eval :

for ( var puzzle in puzzlers )
{
    var a = puzzlers[puzzle](10);
    console.log( a );
}

foreach will work like an iterator calling next automaticaly @edit -- you dont need eval;


you can use

 array[indexOffunction](parameterToPass)...

Here is solution:

var puzzlers = [
  function ( a ) { return 8*a - 10; }, 
  function ( a ) { return (a-3) * (a-3) * (a-3); }, 
  function ( a ) { return a * a + 4; },
  function ( a ) { return a % 5; }
];

alert(puzzlers[puzzlers[1](3)](puzzlers[3](9)));

What about using self executing functions, like this :

var a = 5;
var puzzlers = [ 
    ( function (a) { return 3 * a - 8;} )(a),
    ( function (a) { return (a+2) * (a+2) * (a+2) } )(a),
    ( function (a) { return (Math.pow(a,2) - 9);} )(a),
    ( function (a) { return a % 4;} )(a),
];

console.log(puzzlers);
// OUTPUT:
// [7, 343, 16, 1]

Need Your Help

How to capture only a single click/tap on a MPMoviePlayerController view while controls are hidden?

iphone ipad mpmovieplayercontroller uigesturerecognizer

Previously, I asked about how to capture any touch input on an MPMoviePlayerController's view when the MPMovieControlStyle is set to MPMovieControlStyleNone. It was suggested that I could use a

How to check if an array exist, if not create it, in JavaScript?

javascript arrays

How do I check if a specific array exists, and if not it will be created?