更新时间:2022-05-01 23:10:16
返回
具有与其他语言几乎相同的行为。
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