简体   繁体   English

将参数传递给添加到列表的函数

[英]Passing a parameter to a function that is added to a List

In below code I'm attempting to add a function test to an Array. 在下面的代码中,我试图将功能test添加到数组。 The function test contains a parameter param1 : 功能test包含参数param1

var param1 = "param1"

var fArr = []
fArr.push(test(param1));

for (var i = 0; i < fArr.length; i++) {
  fArr[i](param)
}

function test(param){
  console.log('param is '+param)
}

When I run this code I receive error : 当我运行此代码时,收到错误消息:

Uncaught ReferenceError: param is not defined

How can I pass a parameter to the function that is added to array fArr ? 如何将参数传递给添加到数组fArr的函数?

You're not adding a function to the array. 您没有在数组中添加函数。 You're calling the function, and adding what it returns to the array. 您正在调用该函数,并将返回的内容添加到数组中。 But the function doesn't return anything, so you're pushing undefined onto the array. 但是该函数不返回任何内容,因此您要将undefined推入数组。

What I think you want is: 我认为您想要的是:

var param1 = "param1";

var fArr = [];
fArr.push(function() {
    test(param1));
});

for (var i = 0; i < fArr.length; i++) {
  fArr[i]();
}

function test(param){
  console.log('param is '+param);
}

PS Get out of the bad habit of omitting ; PS摆脱遗忘的坏习惯; at the end of statements. 在声明的末尾。

The error is here: fArr[i](param) . 错误在这里: fArr[i](param) You never initialized variable param . 您从未初始化变量param Are you sure you do not want to use param1 ? 您确定不想使用param1吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM