Javascript/Jquery-如何检查函数是否返回任何值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17288237/
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
Javascript/Jquery-How to check if a function returns any value at all?
提问by seamus
Is there a way to check if a function returns ANY value at all. So for example:
有没有办法检查函数是否返回任何值。例如:
if(loop(value) --returns a value--) {
//do something
}
function loop(param) {
if (param == 'string') {
return 'anything';
}
}
回答by SomeShinyObject
Functions that don't return an object or primitive type return undefined. Check for undefined:
不返回对象或原始类型的函数返回 undefined。检查未定义:
if(typeof loop(param) === 'undefined') {
//do error stuff
}
回答by alex
A function with no return
will return undefined
. You can check for that.
没有的函数return
将返回undefined
。你可以检查一下。
However, a return undefined
in the function body will also return undefined
(obviously).
但是,return undefined
函数体中的a也会返回undefined
(显然)。
回答by Karl-André Gagnon
You can do this :
你可以这样做 :
if(loop(param) === undefined){}
That will work everytime with one exception, if your function return undefined
, it will enter in the loop. I mean, it return something but it is undefined...
每次都会有一个例外,如果您的函数返回undefined
,它将进入循环。我的意思是,它返回一些东西,但它是未定义的......
回答by John Slegers
If you want to do something with the output of your function in the case it returns something, first pass it to a variable and then check if the type of that variable is "undefined"
.
如果你想对函数的输出做一些事情,以防它返回一些东西,首先将它传递给一个变量,然后检查该变量的类型是否为"undefined"
.
Demo
演示
testme("I'm a string");
testme(5);
function testme(value) {
var result = loop(value);
if(typeof result !== "undefined") {
console.log("\"" + value + "\" --> \"" + result + "\"");
} else {
console.warn(value + " --> " + value + " is not a string");
}
function loop(param) {
if (typeof param === "string") {
return "anything";
}
}
}