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];
Just iterate through the array:
for(int i = 0; i < poopSong.Length; i++){
poopSong[i]("poop"); //not poopSong("poop")[i];
}
poopSong is the array, so to get to an item, use an index. And since the items in the array are functions, execute a function with (), passing in a parameter ("value");
poopSong[1]("value");
Now if you want to got through each item, use a loop?
for(var i = 0; i < poopSong.length; i++)
{
poopSong[i]("value");
}
or in the world of functional programing, use forEach
poopSong.forEach(function(item){ item("value"); });
is this what you are really after, cause its pretty basic stuff, or am I missing something.
Secondly, don;t use the word this
as a parameter, its a reserved word and has a whole other context in JavaScript
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.