简体   繁体   中英

Else part is executed even when the if condition is true in Javascript

strong textI want to get the user input and search for it through the array of objects . I use for in to iterate through the array of object and if loop for comparing .If the if condition is true the current object details needs to be displayed to the user and if not found show an error message.My code works fine if only the If condition is provided but if the else condition is provided only the else block is executed always.
My html :

 <input type="text" id="name" placeholder="Name"><br>
 <input type="button" value="Get Pokemon Details" id="pokedetails">

JS:

for (var n in data.pokemon) {
if (data.pokemon[n].name.toLowerCase() === value.toLowerCase()) {
  let a = data.pokemon[n];
  displayDetails(a);
  console.log(a);
  break;
}else {
alert('invalid name');
}}}

My javascript code so long for the viewing purpose i have included in jsfiddle please visit there for the full script file. Click Here to Visit JsFiddle

what was the problem with my code or any solution for this?

This is my first question in Stackoverflow apologies if you find something strange while reading or understanding the question.

Using the temp variable solves the issue.

 var flag=0; for (var n in data.pokemon) { if (data.pokemon[n].name.toLowerCase() === value.toLowerCase()) { flag=1; break; } } if (flag==1){ let a = data.pokemon[n]; displayDetails(a); console.log(a); } else{ alert('Invalid Name'); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM