JavaScript:for循环内部函数根据用户输入停止

时间:2017-10-19 16:22:45

标签: javascript function loops fibonacci

我正在尝试编写一个javascript代码,我可以让用户输入一个数字来多次计算循环。

循环应该按照指定的次数运行Fibonacci数并停止。我被要求将循环放在函数中。

Image of the code

< !DOCTYPE HTML >
  <
  html >
  <
  title > Fibonacci < /title> <
  head >
  <
  script >
  function chkInput() {
    var num1 = document.getElementById = ("userInput").value;
    var outputString = "" + (i);
    var a, b, r;
    a = 0;
    b = 1;
    r = b;
    for (var i = 1; i <= num1; i++) {
      outputString += "</br>" + (r * num1);
      r = a + b;
      a = b;
      b = r;
    }
    document.write(outputString);
  }

  <
  /script> <
  /head> <
  body >
  <
  input type = "text"
id = "userInput" >
  <
  input type = "button"
id = "btn"
value = "Enter"
onclick = "chkInput()" >
  <
  /body> <
  /html>

1 个答案:

答案 0 :(得分:0)

效果很好......其中n是数字元素

function chkInput(){
 var num1 = document.getElementByID =("userInput").value;
  document.write(fibonacci_series(num1 ));
}

&安培;然后the Fibonacci series as per this doc

var fibonacci_series = function (n) 
{
  if (n===1) 
  {
    return [0, 1];
  } 
  else 
  {
    var s = fibonacci_series(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
  }
};

数组fibonacci_series包含系列...&amp;这里的return关键字就像循环停止