-3

Take Input from user is number is in Fibonacci series using JavaScript. I am able to push values in array, but not able to compare

<!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>
krillgar
  • 12,596
  • 6
  • 50
  • 86

1 Answers1

1

You need to use the indexOf function to find whether b is in a or not :

<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>
roberto06
  • 3,844
  • 1
  • 18
  • 29
  • Thanks Man, you simplified it like a charm. – Somesh Pursnani Dec 08 '16 at 13:18
  • Actually, your function would have worked, you just forgot the closing bracket (`}`) of your `for` loop. But `indexOf` is way cleaner to check if a value is in an array than iterating over the said array and checking each value. – roberto06 Dec 08 '16 at 13:20
  • true, in that approach else will be printed many times unless some flag or something taken to suppress multiple else print – Somesh Pursnani Dec 08 '16 at 13:43