一个函数如何操作通过另一个函数传递的参数?Javascript

一个函数如何操作通过另一个函数传递的参数?Javascript,javascript,function,parameter-passing,Javascript,Function,Parameter Passing,抱歉,第一次解释这个问题的尝试很差。试图学习Javascript和代码问题(codewars)中的一个问题让我感到困惑。它表示,编写一个函数,将另一个函数作为参数,并缓存结果,这样,如果发送了相同的参数,则会从缓存中提取返回,并且不会再次调用实际函数。例如: var x = function(a, b) { a * b }; var cachedFunction = cache(x); cachedFunction(4, 5); // function x should be executed

抱歉,第一次解释这个问题的尝试很差。试图学习Javascript和代码问题(codewars)中的一个问题让我感到困惑。它表示,编写一个函数,将另一个函数作为参数,并缓存结果,这样,如果发送了相同的参数,则会从缓存中提取返回,并且不会再次调用实际函数。例如:

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

我不知道如何访问通过cachedFunction发送的参数。目标是写缓存,以便它可以处理具有任意数量参数的函数x。

您所描述的是不可能的


表达式
x(5,4)
在调用
cache()
函数之前进行计算。它没有接收函数。它正在接收值
20

您可以返回如下表:

function x(a,b){
    return [a, b, a*b];
}
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
之后,您可以获得如下参数:

function x(a,b){
    return [a, b, a*b];
}
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

在您的示例中,
cache
只能访问
x
的返回值。它不知道这个返回值是如何计算的(例如,通过调用带有参数的
5,4
)调用
x

您需要将函数及其参数分别传递给
缓存
函数,例如。G详情如下:
函数缓存(func,…params){
//Todo:用params做点什么
返回函数(…参数);
}
函数x(a,b){
返回a*b;
}

log(缓存(x,5,4))
实际上没有将
x
5
4
传递到
缓存
函数。将5和4传递给
x
函数,接收结果,然后将结果传递给
缓存
。(无论如何)你不能。调用
cache
函数时,值为
20
(是
x(5,4)
的结果),它不知道传递给
x
的值是什么,也不知道调用过
x
。另外,
缓存
函数做什么?你应该给它传递一个函数吗?因为现在,你不是。对不起,我第一次尝试理解这个问题和用词回答这个问题是很糟糕的。我已经重写了。不确定是否正确的礼仪是将原文全部删除并重写或进行如此大的编辑。如果我应该做前者,我很抱歉。你的编辑使所有给出的答案无效,因为你的问题现在是一个非常不同的问题。最好恢复编辑并提出新问题。