使用闭包的 Javascript 斐波那契数列

发布于 2024-10-16 10:28:35 字数 287 浏览 2 评论 0原文

我要使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

拔了角的鹿 2024-10-23 10:28:35

闭包背后的基本思想是,由于闭包按值绑定所有本地数据,因此您可以使用它们来初始化然后修改仅属于生成函数的“实例”的本地变量。

因为这看起来像是家庭作业,所以我将使用闭包回答一个不同的问题:使用闭包一次获得一个完美的平方(1、4、9 等)。

function makeSquareIteratorFunction() {
  var squareRoot = 1;

  var getNext = function() {
    // Calculate the number you need to return
    var square = squareRoot * squareRoot;

    // Apply side effects. In this case just incrementing the counter, but with
    // Fibonacci you will need to be a little more creative :-)
    // You might also prefer to do this first. Depends on your approach.
    squareRoot = squareRoot + 1;

    // Return the value
    return square;
  };

  // Return the function object, which can then be called later
  return getNext;
}

// Usage
var getNextSquare = makeSquareIteratorFunction();
alert(getNextSquare()); // 1
alert(getNextSquare()); // 4
alert(getNextSquare()); // 9

现在,值得指出的是,外部函数 (makeSquareIteratorFunction) 中定义的局部变量已本地化并绑定到闭包。因此,如果您多次调用 makeSquareIteratorFunction(),后面的调用将独立于第一个调用:

var getNextSquare1 = makeSquareIteratorFunction();
alert(getNextSquare1()); // 1
alert(getNextSquare1()); // 4
var getNextSquare2 = makeSquareIteratorFunction();
alert(getNextSquare2()); // 1 (!) because it's a new closure, initialized the same way
alert(getNextSquare1()); // 9 (!) because it was "on" 4 last time

希望这有助于解释一下吗?如果没有,请发表评论。 :-)

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.

function makeSquareIteratorFunction() {
  var squareRoot = 1;

  var getNext = function() {
    // Calculate the number you need to return
    var square = squareRoot * squareRoot;

    // Apply side effects. In this case just incrementing the counter, but with
    // Fibonacci you will need to be a little more creative :-)
    // You might also prefer to do this first. Depends on your approach.
    squareRoot = squareRoot + 1;

    // Return the value
    return square;
  };

  // Return the function object, which can then be called later
  return getNext;
}

// Usage
var getNextSquare = makeSquareIteratorFunction();
alert(getNextSquare()); // 1
alert(getNextSquare()); // 4
alert(getNextSquare()); // 9

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 call makeSquareIteratorFunction() multiple times, the later ones will be independent of the first one:

var getNextSquare1 = makeSquareIteratorFunction();
alert(getNextSquare1()); // 1
alert(getNextSquare1()); // 4
var getNextSquare2 = makeSquareIteratorFunction();
alert(getNextSquare2()); // 1 (!) because it's a new closure, initialized the same way
alert(getNextSquare1()); // 9 (!) because it was "on" 4 last time

Hopefully that helps explain it a little? If not, leave a comment. :-)

单挑你×的.吻 2024-10-23 10:28:35

我只是想发布一些最新的答案 - 使用现代 JavaScript 编写的斐波那契闭包更具可读性

function fibonacci() {
    let x = 0;
    let y = 1;
    let z = 0;
    return function getNext() {
        [z, x, y] = [x, y, x + y];
        return z;
    };
}

let fun = fibonacci();

for (let i = 0; i < 10; i++) {
    console.log(fun());
}

I just wanted to post a little bit more up to date answer - the fibonacci closure is more readable written using modern JavaScript

function fibonacci() {
    let x = 0;
    let y = 1;
    let z = 0;
    return function getNext() {
        [z, x, y] = [x, y, x + y];
        return z;
    };
}

let fun = fibonacci();

for (let i = 0; i < 10; i++) {
    console.log(fun());
}
菊凝晚露 2024-10-23 10:28:35
    var fibonacci = (function () {
        var arr = [0, 1];
        return function () {
            var num = arr[arr.length - 1],
                len = arr.length;
            arr.push(arr[len - 1] + arr[len - 2]);
            return num;
        };
    }());

    //test
    var i;
    for (i = 0; i < 10; i++) {
        console.log(fibonacci());
    }
   //1,1,2,3,5,8,13,21,34,55

请参阅 http://sarathsaleem.github.com/JavaScriptTasks/ 中的描述

我这样做是作为答案对于这个问题
编写一个函数,它会先返回两次 1,然后返回 2,然后返回 3,然后返回 5,依此类推(斐波那契数列)。不要使用任何全局变量。

    var fibonacci = (function () {
        var arr = [0, 1];
        return function () {
            var num = arr[arr.length - 1],
                len = arr.length;
            arr.push(arr[len - 1] + arr[len - 2]);
            return num;
        };
    }());

    //test
    var i;
    for (i = 0; i < 10; i++) {
        console.log(fibonacci());
    }
   //1,1,2,3,5,8,13,21,34,55

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.

紧拥背影 2024-10-23 10:28:35
fibonacci = ([f0, f1] = [0, 1]) => () => ([f0, f1] = [f1, f0 + f1])[0];

我只是想给出一个使用现代 JavaScript 编写的更新答案。

fibonacci = ([f0, f1] = [0, 1]) => () => ([f0, f1] = [f1, f0 + f1])[0];

I just wanted to give a more up to date answer written using modern JavaScript.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文