Javascript 检查函数是否返回 true 以执行另一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28069638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if function returns true to execute another function
提问by Anand S
I have written a form validation using JS which ends with return(true);
我已经使用 JS 编写了一个以 return(true); 结尾的表单验证;
function check() {
....validation code
return(true);
}
All I want is, need to check if check() function returns true, I want to execute another function.
我想要的是,需要检查 check() 函数是否返回 true,我想执行另一个函数。
Code I have tried is as follows:
我试过的代码如下:
if(check() === true) {
function() {
//Another function code
}
}
回答by JRulle
回答by Cerbrus
First of all, returnis not a function, you can just do this:
首先,return不是一个函数,你可以这样做:
return true;
Now, to only execute myFunctionif checkreturns true, you can do this:
现在,只执行myFunctionifcheck返回true,你可以这样做:
check() && myFunction()
This is shorthand for:
这是以下的简写:
if(check()){
myFunction();
}
You don't need to compare the return value of checkwith true. It's already an boolean.
您不需要比较checkwith的返回值true。它已经是一个布尔值。
Now, instead of myFunction(), you can have any JavaScript code in that ifstatement. If you actually want to use, for example, myFunction, you have to make sure you've defined it somewhere, first:
现在,myFunction()您可以在该if语句中使用任何 JavaScript 代码,而不是。例如,如果您确实想使用 ,myFunction则必须确保已在某处定义它,首先:
function myFunction() {
// Do stuff...
}
回答by Ian
You just need to modify your first code snippet. returnis a keyword, what you are trying to do is to execute it as a function.
您只需要修改您的第一个代码片段。return是一个关键字,您要做的是将其作为函数执行。
function check() {
....validation code
return true;
}
You'll need to change your 2nd snippet slightly, to execute the function too however... The simplest way is to wrap it as an anonymous function using curly braces:
您需要稍微更改您的第二个代码段,以便也执行该函数...最简单的方法是使用花括号将其包装为匿名函数:
if(check()) {
(function() {
//Another function code
})();
}
回答by Lev Kuznetsov
You're not calling the function in your affirmative clause, only declaring it. To call an anonymous function do this:
你不是在你的肯定子句中调用函数,只是声明它。要调用匿名函数,请执行以下操作:
(function (){...})()

