将函数传递给数组然后调用它

Kei*_*ith 3 javascript

我正在尝试将一个函数添加到数组中,然后稍后调用它.

// So add it here
var list = [{ Name: "Name1", Name2: "Name", Function: test() }]

// Then call it later which will run the function
list.Function;

function test(){
    var test = "test";
    console.log(test);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*yer 5

您可能不希望在将其放入列表时调用该函数,这是您在添加test()到阵列时所执行的操作.这将在您创建列表时将函数调用并将结果添加到列表中.另外,要在引用它时调用它,您需要包含索引:

function test(){
    var test = "test";
    console.log(test);
}
// So add it here
var list = [{ Name: "Name1", Name2: "Name", Function: test }] // just add a reference to test no `()`

// Then call it later which will run the function
list[0].Function();  // list is an array so you need to reference the first item
Run Code Online (Sandbox Code Playgroud)