简体   繁体   English

了解匿名函数的作用域和返回值

[英]understanding the anonymous function scope and return value

I have a function the receives two ints, I want another variable to be initialized with the larger one. 我有一个接收两个整数的函数,我希望另一个变量用较大的变量初始化。

this is the code part: 这是代码部分:

 function findCommonDev(num1, num2) { var res = ((num1, num2) => { if (num1 > num2) { return num1; } else { return num2; } }); console.log(res); } findCommonDev(10,12) 

Now the questions arising from this are not related to the specific code. 现在,由此产生的问题与特定代码无关。

  1. the console.log(res) prints '[function: res]' I would expect res to have the value of the bigger int passed to the function. console.log(res)打印'[function:res]'我希望res具有传递给函数的较大int的值。

  2. I'm writing in VSC and the arguments are not marked as being used meaning that there is shadowing of num1 and num2 - why? 我正在用VSC编写,并且未将参数标记为正在使用,这意味着存在num1和num2的阴影-为什么?

  3. how do I solve this elegantly? 我该如何优雅地解决这个问题?

You need to called the function and pass num1 and num2 as parameters. 您需要调用该函数并将num1num2作为参数传递。

 function findCommonDev(num1, num2) { var res = ((num1, num2) => { if (num1 > num2) { return num1; } else { return num2; } })(num1,num2); console.log(res); } findCommonDev(4,6) 

Also notice that if you don't pass num1 and num2 the code won't work because inside the the function num1 and num2 are local variables and not the variables of outer function. 还要注意,如果不传递num1num2该代码将无法工作,因为在函数num1num2是局部变量,而不是外部函数的变量。

The expected arguments of function are just like local variables. 函数的预期参数就像局部变量一样。 They are created whether parameters are passed or not. 无论是否传递参数都将创建它们。

Beside the returning of a new function (which is the real function for giving the wanted value), you could just take the max value. 除了返回新函数(这是提供所需值的实际函数)之外,您还可以取最大值。

 function findCommonDev(num1, num2) { var res = Math.max(num1, num2); console.log(res); } findCommonDev(3, 42); 

You are giving to console a function reference. 您要给控制台提供功能参考。 However, of you want to run function, then specify parameters: 但是,要运行函数,然后指定参数:

 function findCommonDev(num1, num2) { var res = ((num1, num2) => { if (num1 > num2) { return num1; } else { return num2; } }); return res(num1, num2); }; console.log(findCommonDev(1,2)); 

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

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