我如何通过关闭解决这个问题?

How do I solve this with closure?

我想使用闭包来跟踪所有之前的计算,并使用闭包将它们填充到一个对象中并只打印结果,如果密码被命中,那么它应该用之前的结果来控制整个对象的输出操作。

function saveOutput(func, magicWord) {
  let output = {};
  let outer = magicWord;

  function someWork(x) {
    if (x !== outer) {
      output.x = func(x);
      console.log(output[x]);
    } else {
      console.log(output);
    }
  }
}

// /*** Uncomment these to check your work! ***/
const multiplyBy2 = function(num) {
  return num * 2;
};
const multBy2AndLog = saveOutput(multiplyBy2, 'boo');
console.log(multBy2AndLog(2)); // => should log 4
console.log(multBy2AndLog(9)); // => should log 18
console.log(multBy2AndLog('boo')); // => should log { 2: 4, 9: 18 }

  • 您正在执行 multBy2AndLog。为此,您需要 return 来自 saveOutputsomeWork 函数。
  • 如果你想要multBy2AndLog(2)到return一个值,你需要return output[x]someWork
  • output.x 将向 output 对象添加一个 属性 x。您需要使用方括号 output[x] 添加一个键值在 x (JavaScript property access: dot notation vs. brackets?)

function saveOutput(func, magicWord) {
  let output = {};
  let outer = magicWord;
  
  // ↓ add return here
  return function someWork(x) {
    if (x !== outer) {
      output[x] = func(x); // not output.x
      return output[x]; // <- return the value from the function 
    } else {
      return output;
    }
  }
}

function multiplyBy2(num) {
  return num * 2;
};

const multBy2AndLog = saveOutput(multiplyBy2, 'boo');

console.log(multBy2AndLog(2)); // => should log 4
console.log(multBy2AndLog(9)); // => should log 18
console.log(multBy2AndLog('boo')); // => should log { 2: 4, 9: 18 }