[英]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];
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. poopSong是数组,因此要获取项目,请使用索引。 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 或在函数式编程的世界中,使用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 其次,不要使用
this
词作为参数,它是保留词,并且在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. 首先,您必须更改传递的参数,
this
是一个保留关键字,我认为您不想使用它。 Of course you can refer to this
in the console.log()
. 当然,您可以在
console.log()
引用this
。 However, I don't think that this is what your want. 但是,我认为这不是您想要的。 That being said the declartion of
poopSong
should be something like the following: 话虽这么说,poopSong的
poopSong
应该类似于以下内容:
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.