我必须在 javascript 函数中返回一些东西吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6221784/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:57:09  来源:igfitidea点击:

Do I have to return something in javascript function?

javascriptfunctionreturn

提问by Moon

In JavaScript functions, do I need to return something (true or false) ? So far, all the functions I wrote without returning anything work just fine. I'm just curious.

在 JavaScript 函数中,我是否需要返回某些内容(true 或 false)?到目前为止,我写的所有函数都没有返回任何东西都可以正常工作。我只是好奇。

回答by SLaks

No; Javascript functions are not required to return a value.

不; Javascript 函数不需要返回值。

If you call a function that doesn't returna value, you'll get undefinedas the return value.

如果您调用一个没有return值的函数,您将获得undefined返回值。

回答by hvgotcodes

no you dont. I believe if you do

不,你没有。我相信如果你这样做

var result = iAmADefinedFunctionThatDoesntReturnAnything();

result will be undefined.

结果将是未定义的。

Edit, this screenshot should be illuminating (forgive the mistake when i fail to invoke f):

编辑,这个截图应该是有启发性的(请原谅我未能调用 f 的错误):

enter image description here

在此处输入图片说明

回答by Mina Gabriel

No you don't

不,你没有

BUTif you find yourself doing something like this

但是如果你发现自己在做这样的事情

 function myFun(){
   if (1 == 2){
    return true ;
   }
 }

Now you should know you are doing something wrong in your code because it doesn't make sense that only part of the function return a value

现在您应该知道您在代码中做错了什么,因为只有部分函数返回值是没有意义的