如何在JavaScript中返回值

The best way to pass information back to code that called a function in JavaScript is to write the function so the values that are used by the function are passed to it as parameters and the function returns whatever value it needs to without using or updating any global variables.

将信息传递回JavaScript中称为函数的代码的最好方法是编写函数,以便将函数使用的值作为参数传递给函数,并且函数返回所需的任何值,而无需使用或更新任何全局变量。变量。

By limiting the way in which information is passed to and from functions, it is easier to reuse the same function from multiple places in the code.

通过限制信息与函数之间的传递方式,可以更轻松地从代码的多个位置重用同一函数。

JavaScript返回语句 ( JavaScript Return Statement )

JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running.

JavaScript提供了在需要运行的函数中的所有内容都运行完之后,将一个值传递回调用它的代码。

JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or a calculation where the result of the calculation is returned. For example:

JavaScript通过使用return语句将值从函数传递回调用它的代码。 要返回的值在返回值中指定。 该值可以是常量值 ,变量或返回计算结果的计算。 例如:


return 3;
return xyz;
return true;
return x / y + 27;​You can include multiple return statements into your function each of which returns a different value. In addition to returning the specified value the return statement also acts as an instruction to exit from the function at that point. Any code that follows the return statement will not be run.
function num(x, y) {
if (x !== y) {return false;}
if (x < 5) {return 5;}
return x;
}

The above function shows how you control which return statement is run by using if statements.

上面的函数显示了如何使用if语句控制运行哪个return语句。

The value that is returned from a call to a function is the value of that function call. For example, with that function, you can set a variable to the value that is returned using the following code (which would set result to 5).

从对函数的调用返回的值是该函数调用的值。 例如,使用该函数,可以将变量设置为使用以下代码返回的值(将结果设置为5)。


var resul

The difference between functions and other variables is that the function has to be run in order to determine its value. When you need to access that value in multiple places in your code, it is more efficient to run the function once and assign the value returned to a variable. That variable is used in the rest of the calculations.

函数和其他变量之间的区别在于必须运行该函数才能确定其值。 当您需要在代码中的多个位置访问该值时,一次运行该函数并将返回的值分配给变量会更有效。 该变量将在其余计算中使用。

翻译自: https://www.thoughtco.com/javascript-functions-2037203

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值