当我尝试为我正在做的一些动画填充 JS 数组时,我遇到了这个问题......当我出于测试目的单击网页中的链接时,将调用以下 Javascript 函数:
function testing()
{
var funcArray = [];
var testFunc = function(){console.log("test function");}
funcArray.push(function(){console.log("hello there");});
funcArray.push(testFunc());
}
执行时,我会在 JS 控制台中出现“test function”,但不会出现“hello there”。为什么推送预定义的 testFunc 会导致输出,而不是第一次推送中的内联函数?
最佳答案
因为你正在调用它。
funcArray.push(testFunc());
调用 testFunc,然后将该调用的结果推送到 funcArray 中。您可能需要 funcArray.push(testFunc);
(注意省略的 ()
),它只是将函数引用推送到该数组。
关于javascript - 为什么当我将函数插入 JS 数组时它会执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495421/