简体   繁体   English

函数返回正确的值和“未定义”

[英]Function returns correct value and 'undefined'

I have following code: 我有以下代码:

module = {

        submodule: {

            value: 'foo',

            init: function(){
                console.log(module.submodule.value);
            }

        }

    };

When I'm testing this code through console I get correct value and undefined but when I'm using same code with return statement inside init function I only get correct value. 当我通过控制台测试此代码时,我会得到正确的值和undefined值,但是当我在init函数中使用带有return语句的相同代码时,我只会得到正确的值。 I suppose this is one of those common beginner and trivial questions but I currently can't wrap my head around this :) 我想这是那些常见的初学者和琐碎问题之一,但我目前无法解决这个问题:)

Console return undefined because your method doesn't return any value and the console always output the return of a function when called from the console. 控制台返回未定义,因为您的方法不返回任何值,并且控制台从控制台调用时始终输出函数的返回。

If you add return true in your init method it will output the value and true. 如果在init方法中添加return true ,则将输出值和true。

It's only the behaviour of the console you are seeing nothing wrong. 只是控制台的行为,您看不到任何错误。

Your function isn't returning anything. 您的函数未返回任何内容。 THe console only displays the returned value of the function. 控制台仅显示该函数的返回值。 There is no need for your function to return something, but if you want the console to finally show "value", then use 您的函数无需返回任何内容,但是如果您希望控制台最终显示“值”,则使用

module = {

        submodule: {

            value: 'foo',

            init: function(){
                return module.submodule.value;
            }

        }

    };

What happens is that each function "returns" something. 发生的事情是每个函数“返回”某些东西。 This something can be used as inputs elsewhere. 这可以用作其他地方的输入。 For example, 例如,

function getName(){
return "Manish";
}

alert(getName()) //will display "Manish" sans quotes

You can do stuff like 你可以做类似的事情

function sin(theta){
//do some math voodoo, store result in "result"
return result;
}
alert((sin(theta)*sin(theta)-5)/Math.sqrt(1-sin(theta)*sin(theta))//random thingy

But, if you decide to not let your function return something (or use return; since it can immediately exit the function), it will return an undefined value, since, well, you didn't define what you wanted it to return . 但是,如果您决定不让函数返回某些内容(或使用return;因为它可以立即退出该函数),它将返回一个未定义的值,因为您没有定义您希望它返回的内容 WHich is fine, as long as you don't try to use the returned value. 只要您不尝试使用返回值,就可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM