简体   繁体   English

为什么这个条件在return语句中没有其他作用?

[英]why does this this condition work in return statement without else?

I think that b should always be returned but the condition work both way. 我认为应该总是返回b,但条件都是双向的。 I read it is recommended not to use it after return statements in c.well now I got it return stops the function. 我阅读了建议不要在c.well中的return语句后使用它,现在我知道它的返回停止功能了。

function min(a,b) {
  if(a<b) return a;
  return b; 
}

min(20,94);//20
min(20,4);//4

Because return breaks out of the function completely. 因为return完全脱离了函数。 return b is never hit if return a has already been hit, and return a will only fire if a is less than b . 如果return a已经被命中,则return b不会被命中,而return a只会在a小于b触发。

The return statement ends function execution and specifies a value to be returned to the function caller. return语句结束函数执行并指定要返回给函数调用者的值。

MDN's notes on return MDN return须知

In pseudo-code, your code snippet essentially performs the following: 在伪代码中,您的代码段实质上执行以下操作:

  1. It takes two arguments, a and b . a两个参数ab
  2. It then checks if a is less than b and if so, returns a - the function ends here. 然后,它检查是否a小于b ,如果是,则返回a -功能到此为止。
  3. If the check in part 2. fails, it makes it to this part and returns b . 如果第2部分中的检查失败,它将进入该部分并返回b The function ends here. 该功能到此结束。
min(20, 94)

Here 20 ( a ) is less than 94 ( b ), so part 2's check evaluates to true and 20 is returned. 这里20a )小于94b ),因此第2部分的检查结果为true,并返回20 Nothing else happens. 什么都没发生。

min(20, 4)

Here 20 ( a ) is not less than 4 ( b ), so part 2's check evaluates to false and we move on to part 3 where 4 is returned. 这里20a小于4b ),因此第2部分的检查结果为假,我们继续进行第3部分,返回4 Nothing else happens. 什么都没发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM