[英]Algorithm to call a function inside a function argument in javascript
here is my code problem, There are three arguments in my function x, y
and num
.这是我的代码问题,我的 function x, y
和num
中有三个 arguments 。 num
must be multiplied with x
and y
and return. num
必须乘以x
和y
并返回。
function abc(num, x, y) { return num * x + " " + num * y; } console.log( abc(5, 2, 4) //returns 10 20 ); console.log( abc(5, abc(5, 6, 6), 4) //doesn't return 30 30 20 ) function abc1(num, x, y) { if (isNaN(x)) { return x + " " + y * num; //now it returns 30 30 20 for abc(5,abc(5,6,6),4) } return num * x + " " + num * y; } console.log( abc1(5, 2, 4) //returns 10 20 ); console.log( abc1(5, abc(5, 6, 6), 4) //now it returns 30 30 20 for abc(5,abc(5,6,6),4) )
I also want to know how to achieve if I call the function below (function inside the argument of the same function)-我也想知道如果我调用下面的function怎么实现(函数在同一个函数的参数里面)——
abc(5,abc(abc(5,abc(5,6,6),abc(5,abc(5,6,6),4)))) // it must return something like how abc(5,abc(5,6,6),4) should return 30 30 20
I want when I call the function abc(5,2,abc(5,abc(5,4,4),3))
should return all parameters(except num
) every time like 10 20 20 15
for calling the function - abc(5,2,abc(5,abc(5,4,4),3))
if I place the same function in the function Parameter/arguments.我想当我调用 function abc(5,2,abc(5,abc(5,4,4),3))
应该返回所有参数(除了num
),每次像10 20 20 15
一样调用abc(5,2,abc(5,abc(5,4,4),3))
- abc(5,2,abc(5,abc(5,4,4),3))
如果我在 function 参数/参数中放置相同的 function。
I tried but when I call the function inside the same function arguments like abc(5,abc(5,6,6),4)
the x
in the function abc(num,x,y)
becomes NaN
hence returns like NaN 20
but not 30 30 20
. I tried but when I call the function inside the same function arguments like abc(5,abc(5,6,6),4)
the x
in the function abc(num,x,y)
becomes NaN
hence returns like NaN 20
but不是30 30 20
。
but how to do for this abc(5,abc(abc(5,abc(5,6,6),abc(5,abc(5,6,6),4))))
to return the same way like above.但是如何让这个abc(5,abc(abc(5,abc(5,6,6),abc(5,abc(5,6,6),4))))
以与上面相同的方式返回.
Any online source would help, Thanks.任何在线资源都会有所帮助,谢谢。
You could return an array and check if the value is an array and use the values instead of multiplying with the given factor.您可以返回一个数组并检查该值是否是一个数组并使用这些值而不是与给定因子相乘。
function fn(f, a, b) { return [...(Array.isArray(a)? a: [f * a]), ...(Array.isArray(b)? b: [f * b]), ]; } console.log(...fn(5, 6, 6)); // [30, 30] console.log(...fn(5, fn(5, 6, 6), 4)); // [30, 30, 20] console.log(...fn(5, 2, fn(5, fn(5, 4, 4), 3))); // [10, 20, 20, 15]
An even shorter approach更短的方法
function fn(f, ...values) { return values.flatMap(x => Array.isArray(x)? x: [f * x]); } console.log(...fn(5, 6, 6)); // [30, 30] console.log(...fn(5, fn(5, 6, 6), 4)); // [30, 30, 20] console.log(...fn(5, 2, fn(5, fn(5, 4, 4), 3))); // [10, 20, 20, 15]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.