console.log(myFunction())返回未定义 [英] console.log(myFunction()) returns undefined
问题描述
我是JavaScript的新手,我尝试使用它来了解所有内容。我写了
I'm new to JavaScript, and I try to play around with it to understand all in-and-outs. I write
function greet() {
console.log("Hi");
};
console.log(greet());
它在控制台中的结果是
> Hi app.js:2
> undefined app.js:4
我认为这是因为 greet()<
console.log
中的/ code>首先调用该函数,该函数会打印出 Hi
。我们得到日志的第一行。 但是第二行是哪里来的?
I assume this is because greet()
inside console.log
first calls the function, which prints out "Hi"
. We get first line of log. But where did the second line come from?
然后我想是因为 Hi
是 greet()
的整体结果,然后 console.log
的总体结果基本上称为变量 Hi
,但在这种情况下,结果将是未定义
,而不是未定义
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
推荐答案
在JavaScript中,如果使用关键字 return
的函数未返回任何内容,则<$
In JavaScript, if nothing is returned from the function with the keyword return
then undefined
is returned by default.
var data = greet();
console.log(data);// undefined, since your function does not return.
等效于:
console.log(greet());
第二个输出是该函数返回的结果。由于您没有从该函数返回任何内容,因此会打印 undefined
。
The second output is the returned result from the function. Since you are not returning anything from the function hence prints undefined
.
要在第二个控制台中打印 Hi您必须从函数中返回该值。
To print 'Hi' in the second console you have to return that from the function.
function greet() {
console.log("Hi");
return 'Hi';
};
console.log(greet());
这篇关于console.log(myFunction())返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!