为什么使用return代替console.log? [英] Why is return used instead of console.log?
问题描述
我正在尝试从Codecademy学习JS。我正在此练习。
I'm trying to learn JS from Codecademy. I'm doing this excercise.
有人可以告诉我为什么使用 return
而不是 console.log吗? ()
?
我不完全了解返回
的工作方式。
Can someone please tell me why return
is used instead of console.log()
?
I don't fully understand how return
works.
推荐答案
返回
具有与其他语言几乎相同的行为。
return
has pretty much the same behavior as it does in other languages.
来自返回MDN
在函数中调用return语句时,该函数的执行将停止。如果指定,给定值将返回给函数调用者。如果省略该表达式,则返回undefined。
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.
这基本上是指在调用函数 foo()
具有类似 return 1的语句;
它将具有 1
这样: var bar = foo(); // bar = 1
What this basically means is that when you call a function foo()
that has a statement like return 1;
it will have the value of 1
so: var bar = foo(); // bar = 1
function foo() {
return 1;
}
var bar = foo(); // bar = 1
console.log()
如果您正在控制台中运行该程序,可能会造成混淆,它会将值打印到控制台,因此如果我们之前的函数 foo
是函数foo(){console.log(1); }
我们的 var bar = foo();
实际上会将 bar
设置为未定义
。
console.log()
can be confusing if you're running the program in the console, it prints the value to the console so if our function foo
from before was function foo() { console.log(1); }
our var bar = foo();
would actually set bar
to undefined
.
function foo() {
console.log(1);
}
var bar = foo(); // bar = undefined
这篇关于为什么使用return代替console.log?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!