检查函数是否返回 true 以执行另一个函数

Check if function returns true to execute another function

本文关键字:函数 执行 另一个 返回 是否 检查 true      更新时间:2023-09-26

我用JS写了一个以return(true)结尾的表单验证;

function check() {
  ....validation code
  return(true);
}

我想要的只是,需要检查 check() 函数是否返回 true,我想执行另一个函数。

我尝试过的代码如下:

if(check() === true) {
  function() {
    //Another function code
  }
}
你应该

使用return true;,你的if语句不需要=== true比较。

function check() {
  //validation code
  return true;
}
if(check()) {
  //Another function code
 }

吉斯菲德尔

首先,return 不是函数,你可以这样做:

return true;

现在,要仅在check返回true时才执行myFunction,您可以这样做:

check() && myFunction()

这是以下的简写:

if(check()){
    myFunction();
}

您无需将 check 的返回值与 true 进行比较。它已经是一个布尔值。

现在,您可以在该 if 语句中包含任何 JavaScript 代码,而不是 myFunction() 。例如,如果您实际上想使用 myFunction ,您必须确保在某处定义了它,首先:

function myFunction() {
    // Do stuff...
}

你只需要修改你的第一个代码片段。 return是一个关键字,您要做的是将其作为函数执行。

function check() {
....validation code
return true;
}

您需要稍微更改第二个代码段,也可以执行该函数......最简单的方法是使用大括号将其包装为匿名函数:

if(check()) {
       (function() {
                    //Another function code
       })();
 }

你不是在肯定句中调用函数,只是声明它。要调用匿名函数,请执行以下操作:

(function (){...})()

你可以输入

$this.myFunction=function(){
//code here
}

如果 myFunction 函数为 true,要执行一些代码,您可以使用布尔值例如

if(//your function is true){

等等