最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavascriptJquery-How to check if a function returns any value at all? - Stack Overflow

programmeradmin0浏览0评论

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';
    }
}

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';
    }
}
Share Improve this question asked Jun 25, 2013 at 2:34 seamusseamus 2,9019 gold badges31 silver badges55 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 9

Functions that don't return an object or primitive type return undefined. Check for undefined:

if(typeof loop(param) === 'undefined') {
    //do error stuff
}

A function with no return will return undefined. You can check for that.

However, a return undefined in the function body will also return undefined (obviously).

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...

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".


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";
    }
  }
}

发布评论

评论列表(0)

  1. 暂无评论