I have a simple quesetion and I'm not sure why the array content is not being returned properly. I'm pretty sure this is something simple but somehow I'm not getting the results I want. The scenario is that a variable "compare" is set to a value e.g. "apple" and I am looping into the array, and, if apple matches an index print that into the text field. It doesn't do it and it always says the "not the same" value. For value dog it works. It seems like it reaches the last array then does comparisons. Help please.
Code below
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var text = "";
var i;
var arr = ["apple", "banana", "carrot", "dog"];
var compare = "apple";
for (i = 0; i < arr.length; i++) {
if (arr[i] == compare) {text = "The value is " + arr[i] + "<br>"; }
else if (compare == "" || compare == null) { text = "The value is blank"; }
else if (arr[i] != compare) {text = "not the same"; }
else {text ="some error";}
}
document.getElementById("demo").innerHTML = text;
}
</script>
<p>Click the button to do a loop with a break.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
apple
was the last item in the array. Does that help?else
will never be used, because your previous conditions cover all possibilities. In particular, you have aif (arr[i] == compare)
and aif (arr[i] != compare)
. Unless you were comparing withNaN
(which has the unusual behavior of never being either==
or!=
to anything), one of those two will be true.