JavaScript返回语句

介绍 (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;
    }

Run Code

运行代码

The following function returns the product of its arguments, arg1 and arg2.

以下函数返回其参数arg1arg2的乘积。

function myfunction(arg1, arg2){
       var r;
       r = arg1 * arg2;
       return(r);
    }

Run Code

运行代码

When a function returns 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 returned 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

Run Code

运行代码

翻译自: https://www.freecodecamp.org/news/javascript-return-statements/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值