簡體   English   中英

在 javascript 中的 function 參數中調用 function 的算法

[英]Algorithm to call a function inside a function argument in javascript

這是我的代碼問題,我的 function x, ynum中有三個 arguments 。 num必須乘以xy並返回。

 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) )

我也想知道如果我調用下面的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

我想當我調用 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不是30 30 20

但是如何讓這個abc(5,abc(abc(5,abc(5,6,6),abc(5,abc(5,6,6),4))))以與上面相同的方式返回.

任何在線資源都會有所幫助,謝謝。

您可以返回一個數組並檢查該值是否是一個數組並使用這些值而不是與給定因子相乘。

 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]

更短的方法

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM