[英]How can a function manipulate parameters passed via another function? Javascript
Sorry, first attempt at explaining this question was poor. 抱歉,第一次尝试解释这个问题很糟糕。 Trying to learn Javascript and a question from a code problem (codewars) has me stumped. 试图学习Javascript和代码问题(codewars)的问题令我感到困惑。 It states, write a function that takes another function as a parameter and caches results so that if the same parameters are sent then the return is pulled from the cache and the actual function is not invoked again. 它声明,编写一个将另一个函数作为参数并缓存结果的函数,这样,如果发送了相同的参数,则从缓存中提取返回值,并且不会再次调用实际函数。 For example: 例如:
var x = function(a, b) { a * b };
var cachedFunction = cache(x);
cachedFunction(4, 5); // function x should be executed
cachedFunction(4, 5); // function x should not be invoked again, instead the cached result should be returned
cachedFunction(4, 6); // should be executed, because the method wasn't invoked before with these arguments
I am not sure how to access the arguments sent via cachedFunction. 我不确定如何访问通过cachedFunction发送的参数。 The goal is to write cache so that it can handle a function x with any number of arguments. 目的是编写缓存,以便它可以处理具有任意数量参数的函数x。
What you're describing is not possible. 您所描述的是不可能的。
The expression x(5, 4)
is evaluated before the cache()
function is even called. 甚至在调用cache()
函数之前先对表达式x(5, 4)
求值。 It's not receiving a function. 它没有收到功能。 It's receiving the value 20
. 它正在接收值20
。
In your example, cache
only has access to the return value of x
. 在您的示例中, cache
仅有权访问x
的返回值。 It can't know anything about how this return value was computed (ie by calling x
with parameters 5, 4
). 它不能(通过调用即知道这个返回值是如何计算的东西x
与参数5, 4
)。
You would need to separately pass the function and its parameters to the cache
function, eg as follows: 您将需要将函数及其参数分别传递给cache
函数,例如,如下所示:
function cache(func, ...params) { // Todo: do something with params return func(...params); } function x(a, b){ return a * b; } console.log(cache(x, 5, 4));
you can return a table like this: 您可以返回如下表:
function x(a,b){
return [a, b, a*b];
}
after that you can get the params like this: 之后,您可以得到如下的参数:
var result=x(values1,value2);
console.log(result[0]);// a == value1
console.log(result[1]);// b == value2
console.log(result[2]);// a*b == value1*value2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.