检查JavaScript中的Fibonnaci是否为数字

时间:2016-12-08 13:05:44

标签: javascript

从用户输入输入数字是使用JavaScript的Fibonacci系列。 我能够在数组中推送值,但无法比较

<!DOCTYPE html>
<html>
  <head>
    <script>
      var a = new Array();
      var b = prompt("Enter Number");
      var i = 0,
        j = 1,
        k = 0,
        l;
      while (k < 100) {
        a.push(k)
        document.write(k + " ")
        k = i + j;
        i = j;
        j = k;
      }
      document.write("<br>" + a[4] + a.length);
      //
      for (l = 0; l <= a.length; l++) {
        if (a[l] == b) {
          document.write(a[l]);
        }
    </script>
  </head>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要使用indexOf功能查找b是否在a中:

<script>
var a = new Array();
var b = prompt("Enter Number");

var i=0,j=1,k=0,l;

while(k < 100) {
    a.push(k)
    document.write(k + " ")
    k = i+j;
    i=j;
    j=k;
}

b = parseInt(b); // Necessary for comparison
var index = a.indexOf(b);
if (index != -1) {
    alert (b + ' is in position ' + index + ' of the array');
} else {
    alert (b + ' is not in the array');
}
</script>