-3

I'm pretty new to JavaScript and I'm not quite sure what I'm doing wrong, any help would be much appreciated.

var array = [3, 5, 6, 10, 20];

function array (arr, num) {
    for (var i=0 ;  i < array.length; i++);
    return true;
} else {
    return false;
}
}

arr(10);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • `arr(10);` Your function is named `array` (which is a bad choice), not `arr`, and it expects two parameters. – j08691 Jul 12 '18 at 14:05
  • It looks like you probably need to review how for loops work. Anyways, you need to have a condition that checks all the indices' values against the number parameter, you can do this for each iteration of the for loop. You should also name your functions appropriately, like what the function is actually supposed to do. – dave Jul 12 '18 at 14:05
  • var array, function arrray, arr??? no if? You have many mistakes.... – epascarello Jul 12 '18 at 14:06
  • your check condition is **missing**. Also, do not use `array` as a function name – BlackBeard Jul 12 '18 at 14:06
  • where is the IF part? – alec_djinn Jul 12 '18 at 14:07
  • Check which `}` corresponds to which `{` and I'm sure you'll realize why your syntax is messed up. – Lennholm Jul 12 '18 at 14:09

2 Answers2

-1

Use indexOf to check if an Object is in an Array. indexOf will return the index of the element if it is in the Array and -1 if it is not.

 function arrayContains(arr, obj) {
   return arr.indexOf(obj) != -1;
  }

<input type="text" id="num">
<br/>
<input type="button" value="Check if value is one of the first nine terms of the Fibonacci sequence" onClick="check()"/> 
<br/>
<span id="result"></span>
<script>
var array = [1, 1, 2, 3, 5, 8, 13, 21, 34];
function arrayContains(arr, obj) {
       return arr.indexOf(obj) != -1;
}
var result = document.getElementById("result");
function check(){
   var num = document.getElementById("num").value;
   if(num.trim().length&&!isNaN(num)){
     if(arrayContains(array, parseInt(num, 10))){
       result.innerHTML = "Number is one of the first nine terms of the Fibonacci sequence.";
     } else {
     result.innerHTML = "Number is <b>not</b> one of the first nine terms of the Fibonacci sequence.";
     }
   } else {
    result.innerHTML = "<b style='color: red;'>Input must be a number!</b>";
   }
}
</script>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
-2

You don't really have to use a loop for that. You can use the indexOf() function. https://www.w3schools.com/jsref/jsref_indexof_array.asp

Your code will looks like:

var numbers = [3, 5, 6, 10, 20];
function isNumberInList(numbers, number) {
  var result = false;
  if(numbers.indexOf(number)!=-1){
     result = true;
  }
  return result;
}
WEGSY85
  • 291
  • 1
  • 3
  • 21