使用闭包的 Javascript 斐波那契数列
我要使用 Javascript 编写一些代码。这是我们要做的:
“使用闭包实现 javascript 斐波那契数。具体来说,编写一个函数来存储两个连续的斐波那契数,最初是 0 和 1。该函数还定义并返回一个嵌套函数 getNext()。 getNext( ) 函数将两个存储的斐波那契数更新为接下来的两个斐波那契数,并返回当前的斐波那契数,例如,第一次调用 getNext() 时,返回值为 0,下一次调用时,返回值为 1,然后再次为 1,最后为 2。 ETC。”
我有点理解这一点,但不是真的。有人可以帮忙澄清一下吗?谢谢!
I am to write up some code using Javascript. Here is what we are to do:
"Implement a javascript Fibonacci numbers using closures. Specifically, write an function that stores two consecuitive Fibonacci numbers, initially 0 and 1. The function also defines and returns a nested function getNext(). The getNext() function updates the two stored Fibonacci numbers to the next two Fibonacci numbers and returns the current one. E.g. on the first call to getNext() the return value is 0, on the next call it is 1, then 1 again, then 2, etc."
I kind of understand this but not really. Could someone maybe help clarify? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
闭包背后的基本思想是,由于闭包按值绑定所有本地数据,因此您可以使用它们来初始化然后修改仅属于生成函数的“实例”的本地变量。
因为这看起来像是家庭作业,所以我将使用闭包回答一个不同的问题:使用闭包一次获得一个完美的平方(1、4、9 等)。
现在,值得指出的是,外部函数 (makeSquareIteratorFunction) 中定义的局部变量已本地化并绑定到闭包。因此,如果您多次调用 makeSquareIteratorFunction(),后面的调用将独立于第一个调用:
希望这有助于解释一下吗?如果没有,请发表评论。 :-)
The basic idea behind closures is that, since closers bind all local data by value, you can use them to initialize and then modify variables that are only local to that "instance" of the generated function.
Since this seems like homework, I'm going to answer a different question using closures: Use closures to get perfect squares (1, 4, 9, etc.), one at a time.
Now, it's worth pointing out that the local variables defined in the outer function (
makeSquareIteratorFunction
) are localized and bound to the closure. So if you callmakeSquareIteratorFunction()
multiple times, the later ones will be independent of the first one:Hopefully that helps explain it a little? If not, leave a comment. :-)
我只是想发布一些最新的答案 - 使用现代 JavaScript 编写的斐波那契闭包更具可读性
I just wanted to post a little bit more up to date answer - the fibonacci closure is more readable written using modern JavaScript
请参阅 http://sarathsaleem.github.com/JavaScriptTasks/ 中的描述
我这样做是作为答案对于这个问题
编写一个函数,它会先返回两次 1,然后返回 2,然后返回 3,然后返回 5,依此类推(斐波那契数列)。不要使用任何全局变量。
See the description in http://sarathsaleem.github.com/JavaScriptTasks/
I did this as an answer to this question
Write a function which will return you first two times 1, then 2, then 3, then 5 and so on (Fibonacci numbers). Don’t use any global variables.
我只是想给出一个使用现代 JavaScript 编写的更新答案。
I just wanted to give a more up to date answer written using modern JavaScript.