简体   繁体   English

了解JavaScript memoized函数中的输入值

[英]Understanding input value in JavaScript memoized function

I am currently going through 'Javascript: The good parts' by Douglas Crockford, an there is an example demonstrating the concept of memoization. 我目前正在阅读道格拉斯·克罗克福德的“Javascript:好的部分”,这是一个展示记忆概念的例子。

var memoizer = function (memo, fundamental) {
  var shell = function (n) {
   var result = memo[n];
   if (typeof result !== 'number') {
     result = fundamental(shell, n);
     memo[n] = result;
   }
  return result;
  };
return shell;
};

var fibonacci = memoizer([0, 1], function (shell, n) {
   return shell(n - 1) + shell(n - 2);
});

What I don't understand is, where is the value for n coming from? 我不明白的是, n的价值来自哪里?

n is an input. n是输入。 It doesn't "come" from any where in the code you've posted, you have to supply it a value. 它不是来自您发布的代码中的任何位置,您必须为其提供值。

In the code var shell = function (n) , you're specifying that when you call the function shell , you're going to provide it with an input argument n . 在代码var shell = function (n) ,您指定在调用函数shell ,您将为其提供输入参数n So if you called shell(5) , n would be equal to 5, or any other number that you passed in. 因此,如果您调用shell(5) ,则n将等于5,或者您传入的任何其他数字。

You need to look at what's being called and returned in each function call -- fibonacci is set to the returned value of the memoizer function, and memoizer returns the shell function which takes in n . 你需要查看每个函数调用中调用和返回的内容 - fibonacci设置为memoizer函数的返回值, memoizer返回memoizer nshell函数。 So although it's never called in your example code, in the end you'd call, say, fibonacci(5) where 5 is your n . 因此,虽然它从未在您的示例代码中调用过,但最后您会调用fibonacci(5) ,其中5是您的n Just follow the function calls and returns. 只需按照函数调用并返回即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM