Javascript function always returns null

前端 未结 4 454
遥遥无期
遥遥无期 2021-01-20 02:04

I am newbie to the JavaScript world. I have a doubt how the return statement works in JavaScript.

What I am trying to do is to have a function pass one arguments

相关标签:
4条回答
  • 2021-01-20 02:37

    There are a few issues with your approach:

    1. The inner function you defined is returning to $.each, not to the outer function, so you never get that value.
    2. You don't need to iterate over the object in the wild way you are. Objects in Javascript are hash tables, you can simply do the following

    :

    function exampleFunction(param) {
        return exampleData[param];
    }
    

    If exampleData[param] is undefined, it will return undefined, otherwise, it will return the value stored there.

    If you absolutely need the undefined case to return null instead of undefined, then it becomes a bit more complicated.

    function exampleFunction(param) {
        if(exampleData.hasOwnProperty(param) {
            return exampleData[param];
        } else {
            return null;
        }
    }
    
    0 讨论(0)
  • 2021-01-20 02:49

    Given Crazy Train's comment, you need to capture the matching value so you can return it later:

    function exampleFunction(param) {
        var match = null;
        $.each(exampleData, function (key, value) {
            if (key == param) {
                match = value;
                return false; // to end the $.each early
            }
        });
        return match;
    }
    
    0 讨论(0)
  • 2021-01-20 02:49

    Try this:

    function exampleFunction(param){ 
        return exampleData[param];
      }
    

    EDIT: If you want to return null if the parameter is undefined, then take a look at Paul and Crazy Train's comments:

    return (typeof exampleData[param] === 'undefined')? null: exampleData[param]; 
    

    OR

    return (param in exampleData) ? exampleData[param] : null;
    
    0 讨论(0)
  • 2021-01-20 02:52

    Your example doesn't seem to need a loop. That and returning from the loop-delegate doesn't do anything for you.

    You can test if a key appears in an object using the in operator.

    function exampleFunction(param){
      return param in exampleData ? exampleData[param] : null;
    }
    
    0 讨论(0)
提交回复
热议问题