为什么我的函数执行时,我把它推到一个JS数组

Why does my function execute when I push it onto a JS array?

本文关键字:数组 JS 一个 执行 函数 我的 为什么      更新时间:2023-09-26

我在尝试填充一些动画的JS数组时遇到了这个问题....当我为了测试的目的点击网页中的链接时,调用以下Javascript函数:

function testing()
{
    var funcArray = [];
    var testFunc = function(){console.log("test function");}
    funcArray.push(function(){console.log("hello there");});
    funcArray.push(testFunc());
}

当这个执行时,我得到"测试函数"出现在JS控制台中,但不是"你好"。为什么推送预定义的testFunc会导致输出,而不是第一次推送中的内联函数?

因为你在调用它

funcArray.push(testFunc());

调用 testFunc,然后将该调用的结果推入funcArray。您可能需要funcArray.push(testFunc);(注意省略了()),它只是将函数引用推入该数组。

因为你在funcArray.push(testFunc());中执行它…你想要的是funcArray.push(testFunc);,因为testFunc()执行函数,接受返回并将其推入数组,而testFunc接受实际的函数来推入。