使用 javascript 中的循环查找第 n 个斐波那契数列

finding the nth term fibonacci sequence using loop in javascript

我是 Javascript 的新手,我想问你如何制作一个简单的斐波那契生成器,当用户输入任何数字时,它会找到第 n 项斐波那契数列。给出了示例代码。

<html>
<body>
the number inserted in this textbox will find the nth term of the fibonacci sequence. The sample is 4 where the 4th term is 5. 
<script type="text/javascript">
function myFunction() {
var x = document.f1.n1.value;
if(x=4) {

document.write(5);
}
}
</script>
<form name="f1" onsubmit="return false">
First no. <input type="text"name="n1" value=3 disabled>
<input type="submit" value=GO onClick="myFunction()">
</form>
</body>
</html>
document.write(getAmount(x));

function getAmount(x) {
    if(x < 3) {
        return 1;
    } else { 
        return getAmount(x - 1) + getAmount(x - 2);
    }
}

不确定是否全部正确notation/language但这就是您需要的逻辑。

这是一个递归调用的工作示例:

function myFunction(getLucas) {
  var x = document.f1.n1.value;
  if (getLucas) {
      alert(lucas(x));
  }
  else {
      alert(fib(x));
  }
}

function fib(n) {
  if (n < 2) {
      return n;
  }
  else {
      return fib(n - 1) + fib(n - 2);
  }
}

function lucas(n) {
  if (n < 2) {
      return 2-n;
  }
  else {
      return lucas(n - 1) + lucas(n - 2);
  }
}
<form name="f1" onsubmit="return false">
  First no.
  <input type="text" name="n1" value="3">
  <input type="submit" value="Fibonacci" onClick="myFunction()">
  <input type="submit" value="Lucas" onClick="myFunction(true)">
</form>