介绍 (Introduction)
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.
当在函数中调用return语句时,该函数的执行将停止。 如果指定,给定值将返回给函数调用者。 如果省略表达式,则返回undefined
。
return expression;
Functions can return:
函数可以返回:
- Primitive values (string, number, boolean, etc.) 基本值(字符串,数字,布尔值等)
- Object types (arrays, objects, functions, etc.) 对象类型(数组,对象,函数等)
Never return something on a new line without using parentheses. This is a JavaScript quirk and the result will be undefined. Try to always use parentheses when returning something on multiple lines.
在不使用括号的情况下,切勿在换行符上返回任何内容。 这是一个JavaScript怪癖,结果将是不确定的。 返回多行内容时,请尝试始终使用括号。
function foo() {
return
1;
}
function boo() {
return (
1
);
}
foo(); --> undefined
boo(); --> 1
例子 (Examples)
The following function returns the square of its argument, x, where x is a number.
以下函数返回其参数x的平方,其中x是一个数字。
function square(x) {
return x * x;
}
The following function returns the product of its arguments, arg1 and arg2.
以下函数返回其参数arg1和arg2的乘积。
function myfunction(arg1, arg2){
var r;
r = arg1 * arg2;
return(r);
}
When a function return
s a value, the value can be assigned to a variable using the assignment operator (=
). In the example below, the function returns the square of the argument. When the function resolves or ends, its value is the return
ed value. The value is then assigned to the variable squared2
.
当函数return
sa值时,可以使用赋值运算符( =
)将值赋给变量。 在下面的示例中,该函数返回参数的平方。 当函数解析或结束时,其值为return
ed值。 然后将该值分配给变量squared2
。
function square(x) {
return x * x;
}
let squared2 = square(2); // 4
If there is no explicit return statement, meaning the function is missing the return
keyword, the function automatically returns undefined
.
如果没有显式的return语句,则意味着该函数缺少return
关键字,该函数将自动返回undefined
。
In the following example, the square
function is missing the return
keyword. When the result of calling the function is assigned to a variable, the variable has a value of undefined
.
在以下示例中, square
函数缺少return
关键字。 将调用函数的结果分配给变量时,该变量的值为undefined
。
function square(x) {
let y = x * x;
}
let squared2 = square(2); // undefined
翻译自: https://www.freecodecamp.org/news/javascript-return-statements/