简体   繁体   中英

For loop with if else statement not iterating over entire array

I have been beating my head agains the wall with a basic JS for loop and if else statement. Unfortunately I can not figure it out so I am kindly seeking you advice.

I have added the code below and this is a link to jsfiddle - https://jsfiddle.net/mauro_nappolini/wv5ae1y2/25/#&togetherjs=FFtkmLmEvo

I have an for loop with a nested if else statement which is which does not iterate over the entire array. The for loop stops when the statement returns true and does not iterate over the remaining items in the array.

//Loops through and retrieves all emails from a class of jobemail and adds it to an 
array
var allEmails = $(".jobemail").map(function() {
  return this.innerHTML;
}).get();

//Gets the email that we want to use during comapariosion 
let membersEmail = $('.email-comparison').html();

//New array for all matching emails
let newArray = [];
console.log(membersEmail);
console.log(newArray);

//Loops through new array - shows only matching emails and hides emails that do not 
match
for (let i = 0; i < allEmails.length; i++) {
  console.log(allEmails[i]);
  if (allEmails[i] == membersEmail) {
    //Show matching email content container when jobeemail and email-comparison matches
    $(".email-content-container").show();
    newArray.push(allEmails[i])
  } else {
    //Hide matching email content container when jobeemail and email-comparison matches
    $(".email-content-container").hide();

  }
}
console.log(newArray);

What you should do is hide all before the loop, and then show the matching ones in the loop

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