简体   繁体   中英

Using for loop to calculate a specific step of fibonacci with JavaScript

I'm trying to make an alert which will tell you the n'th step of Fibonacci using a for loop. What I have so far is

var x=1;
var y=1;

var call = function(n) {
    if (n===1||2) {
          alert(1);
        }
    else {
    for(i=3; i<n+1; i++) {
          y=(x+y);
          x=y-x;
          if (i===n) {
            alert(y);
          }
      }
  }
};
call(prompt("Calculate Fibonacci to how many steps?"));

How I've tried to make it work is:

  1. Set variable x and y to 1
  2. Create a function named call which does the following:
  3. Check if the number provided when the function is called is 1 or 2, if so alert 1 (1 being the first two steps of Fibonacci)
  4. If n is not 1 or 2, start for loop at count=3
  5. if count is less than one more than the called step run the following:
  6. add x and y together
  7. set y to this total
  8. set x to the total, minus x
  9. if the count is equal to the step called, alert with the total
  10. add one to the count, go through loop again

But I'm always alerted with 1, even if I change the alert from the first if statement from 1 to a string. I'm not sure if there's an error in the code or in the logic of it.

I've seen a for loop isn't the most efficient way to do this, but I'd like to get it to work this way for learning's sake. I'm only a few lessons in Code Academy so my experience is very limited. Other pages that address this or a very similar problem are

Fibonacci calculator steps
http://ecomputernotes.com/js/javascript-tutorial/javascript-for-loop
https://answers.yahoo.com/question/index?qid=20091001160834AA5xiZ1

This

if (n===1||2) {

needs to be

if (n===1||n===2) {

Your code is evaluating the truthiness of 2, which is always true.

Also, it's unnecessary to evaluate i===n during each iteration. This will be true only after the last iteration of the loop, so just alert(y) after the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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