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

How can a function manipulate parameters passed via another function? Javascript

本文关键字:函数 Javascript 另一个 参数 操作 一个 何操作      更新时间:2023-09-26

抱歉,第一次尝试解释这个问题很糟糕。 试图学习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

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

你所描述的是不可能的。

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

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

您需要将函数及其参数分别传递给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));

你可以返回一个这样的表:

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