Hi I'm following a Webdev Course on udemy. As an exercise we had to identify a missing number from an array and so the solution was like this :
var numbers = [4, 8, 9, 12, 19, 7, 3, 15, 2, 17, 20, 1, 11, 5, 10, 13, 16, 14, 18]
function missingno(numbers){
var missing = - 1
for (var i=0; i <= numbers. length; i++){
if(numbers.indexOf(i) === -
1){
missing = i
}
}
return missing
}
console.log(missingno(numbers))
I don't understand why the index of the missing numbers is - 1. Is it a rule? or is there a mathematical logic to it? And if so, what would be that logic?
My brain is smoking right now.
If anyone can take the time to explain, it would be greatly appreciated.
Peace!
Top comments (4)
The indexOf() method returns the position of the first occurrence of a specified value.
This method returns -1 if the value to search for never occurs.
Ok, so it's just a rule that I should remember :) Thank you so much.
Javascript is a mystic beast ;-)
When in doubt about a function I typically turn to w3schools
I will add that to my bookmarks. Thanks!