Javascript 在 if 语句中使用函数的返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6706360/
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
Using function's return value in if statement
提问by waxical
Hopefully a quick question here.
希望这里有一个快速的问题。
Can you use a function's returned value in a if statement? I.e.
你能在 if 语句中使用函数的返回值吗?IE
function queryThis(request) {
return false;
}
if(queryThis('foo') != false) { doThat(); }
Very simple and obvious I'm sure, but I'm running into a number of problems with syntax errors and I can't identify the problem.
我敢肯定,这非常简单明了,但是我遇到了许多语法错误的问题,而且我无法确定问题所在。
回答by VMAtm
You can simply use
你可以简单地使用
if(queryThis('foo')) { doThat(); }
function queryThis(parameter) {
// some code
return true;
}
回答by Saeed Neamati
Not only you can use functions in if
statements in JavaScript, but in almost all programming languages you can do that. This case is specially bold in JavaScript, as in it, functions are prime citizens. Functions are almost everything in JavaScript. Function is object, function is interface, function is return value of another function, function could be a parameter, function creates closures, etc. Therefore, this is 100% valid.
不仅您可以if
在 JavaScript 的语句中使用函数,而且在几乎所有的编程语言中都可以这样做。这种情况在 JavaScript 中特别大胆,因为在其中,函数是主要公民。函数几乎是 JavaScript 中的一切。函数是对象,函数是接口,函数是另一个函数的返回值,函数可以是参数,函数创建闭包等。因此,这是 100% 有效的。
You can run this example in Firebug to see that it's working.
您可以在 Firebug 中运行此示例以查看它是否正常工作。
var validator = function (input) {
return Boolean(input);
}
if (validator('')) {
alert('true is returned from function');
}
if (validator('something')) {
alert('true is returned from function');
}
Also as a hint, why using comparison operatorsin if
block when we know that the expression is a Boolean expression?
同样作为提示,当我们知道表达式是布尔表达式时,为什么要在块中使用比较运算符if
?
回答by Pete Duncanson
In sort, yes you can. If you know it is going to return a boolean you can even make it a bit simpler:
排序,是的,你可以。如果你知道它会返回一个布尔值,你甚至可以让它更简单一点:
if ( isBar("foo") ) {
doSomething();
}
回答by Jonathan van de Veen
This should not be a problem. I don't see anything wrong with the syntax either. To make sure you could catch the return value in a variable and see if that solves your problem. That would also make it easier to inspect what came back from the function.
这应该不是问题。我也没有看到语法有什么问题。确保您可以捕获变量中的返回值并查看是否可以解决您的问题。这也将使检查从函数返回的内容变得更加容易。
回答by Barry Kaye
Yes you can provided it returns a boolean in your example.
是的,您可以提供它在您的示例中返回一个布尔值。