I am trying to find a number by using the input to search in the array. Got any idea why this does not work?
Every time i run the code i only get the message:
"Number does not exist"
var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var number = document.getElementById("find").value;
var svar = "";
function exists(){
for(i=0; i < arr.length; i++){
if(parseInt(arr[i]) == parseInt(number)){
svar++;
document.getElementById("existsArray").innerHTML = tall + "Number exists";
} else {
document.getElementById("existsArray").innerHTML = tall + "Number does not exist";
}
}
}
<p id="existsArray"></p>
<input placeholder="what number would you like to find?" id="find" type="number">
<button type="button" onclick="exists()">Finn tallet</button>
breakonce you find the matching element. You are still running through the array so it won't work unless the last element in your array is the one that matches.parseIntthem. Also, sincenumberisn't going to change in the loop, you only need toparseIntit once and then use that value in the loop. Lastly you could use Array.prototype.find or Array.prototype.indexOf to make this much simpler.