简体   繁体   English

console.log(myFunction()) 返回未定义

[英]console.log(myFunction()) returns undefined

I'm new to JavaScript, and I try to play around with it to understand all in-and-outs.我是 JavaScript 的新手,我尝试使用它来了解所有的进出。 I write我写的

function greet() {
    console.log("Hi");
};

console.log(greet());

And the result of it in the console is它在控制台中的结果是

> Hi app.js:2 
> undefined app.js:4

I assume this is because greet() inside console.log first calls the function, which prints out "Hi" .我认为这是因为console.log中的greet()首先调用了 function,它会打印出"Hi" We get first line of log.我们得到第一行日志。 But where did the second line come from?但是第二行是从哪里来的呢?

Then I thought because Hi is overall result of greet() , then console.log basically calls variable Hi , but in this case the result would be is not defined , not undefined然后我想因为Higreet()的整体结果,然后console.log基本上调用变量Hi ,但在这种情况下结果将is not defined ,不是undefined

In JavaScript, if nothing is returned from the function with the keyword return then undefined is returned by default.在 JavaScript 中,如果使用关键字return的函数没有返回任何内容,则默认返回undefined

var data = greet();
console.log(data);// undefined, since your function does not return.

Is equivalent to:相当于:

console.log(greet());

The second output is the returned result from the function.第二个输出是函数的返回结果。 Since you are not returning anything from the function hence prints undefined .由于您没有从函数返回任何内容,因此打印undefined

To print 'Hi' in the second console you have to return that from the function.要在第二个控制台中打印“Hi”,您必须从函数中返回它。

 function greet() { console.log("Hi"); return 'Hi'; }; console.log(greet());

You should use a return keyword like this:您应该使用这样的return关键字:

function greet() {
   console.log("HI");
   return "HI";
};
console.log(greet());

Or you can store it in a variable and return the variable :或者您可以将其存储在变量中并返回变量

function greet() {
   const hello = ("HI");
   return hello;
};
cosnole.log(greet());

,Because if you don't use return keyword and log the function to the console then it returns undefined . ,因为如果你不使用return 关键字并将函数记录到控制台然后它返回undefined

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

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