I'm trying to use window.location.href in a Loop

Viewed 199

I want to redirect a user to a new page if their login details are correct. However, when I use the window.location.href("portal.html") in a simple if statement to check if user details match an already stored data in a variable, it works, but when I use it in a for loop to loop through an array of stored data it doesn't render the the portal.html page.

please help, Thanks.

 for(let i = 0; i<= objPeople.length; i++){
      if(name === objPeople[i].username && pass === objPeople[i].password){
        window.location.href="portal.html"
        
        return
      
      }
     
    } console.log("incorrect login details");

3 Answers

Try it like this

 let matches = false;
 for(let i = 0; i<= objPeople.length; i++){
  if(name === objPeople[i].username && pass === objPeople[i].password){
   matches = true;
  
  }
} 
if(matches){
 window.location.href="portal.html"
}

Use find instead of a for loop:

if (objPeople.find(x => x.username === name && x.password === pass))
  window.location.href="portal.html"
else
  console.log("incorrect login details")

I tested your code and like Adnan Ahmed mentioned it does not work because of the return statement. It should be break.

Just remove return. return statement prevents the redirection to the new page. I tried following example and it works:

for (let i = 0; i < 20; i++) {
  if (i === 10)
    window.location.href = "https://google.com";
}

Related