【问题标题】:Why does my function execute when I push it onto a JS array?为什么我的函数在我将它推送到 JS 数组时会执行?
【发布时间】:2015-07-18 20:46:08
【问题描述】:

我在尝试为我正在做的一些动画填充 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);
  • 因为您正在使用 () 执行函数
  • 明白。非常感谢。

标签: javascript jquery arrays function


【解决方案1】:

因为你在调用它。

funcArray.push(testFunc());

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-12
      • 2020-02-25
      • 2016-04-22
      • 2021-03-07
      • 2017-12-28
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多