Sony ThePony Sony ThePony - 15 days ago 6
Javascript Question

How do I pass in a parameter to a function in an array?

So let's say I have an array of functions. How do I pass each function a value?

Here is a silly example:

var poopSong =[

function(this){ console.log('this is '+this);},
function(this){ console.log('that is '+this);},
function(this){ console.log('you are '+this);},

];

poopSong("poop")[1];

Answer

First of all, you have to change the parameter you pass, this is a reserved keyword and I don't think you want to use it. Of course you can refer to this in the console.log(). However, I don't think that this is what your want. That being said the declartion of poopSong should be something like the following:

var poopSong = [
    function(a){ console.log('this is '+a);},
    function(b){ console.log('that is '+b);},
    function(c){ console.log('you are '+c);},
];

Then you can pass an argument to these functions as below:

poopSong[0]('you value');

We use the square brackets and an index to get an item of an array and since in our case the item is a function we can call it using parentheses and passing the corresonding arguments.

var poopSong =[
    function(a){ console.log('this is '+a); },
    function(b){ console.log('that is '+b); },
    function(c){ console.log('you are '+c); }
];

poopSong[0]("1");
poopSong[1]("2");
poopSong[2]("3");

Comments