Browse array to find a particular index

Asked

Viewed 262 times

0

I have the following code JS:

var botao = document.querySelector('input[type="submit"]');

    botao.addEventListener('click', function(e) {
        let form = document.querySelector('form');

        let ipt = {
             nome: form.nome.value,
             senha: form.senha.value                 
        }

        var users = [
          {nome: "Jorge", senha: "123"},
          {nome: "Joao", senha: "joao"},
          {nome: "Maria", senha: "maria"},
          {nome: "José", senha: "jose"},
          {nome: "Ana", senha: "ana"},
        ]

            for(let i = 0; i<users.length; i++) {                           
                if (ipt.nome == users[i].nome && ipt.senha == users[i].senha) {
                    e.preventDefault();
                    alert('Bem vindo ' + form.nome.value + " !");
                    window.location.href= "http://www.google.com";                       
                }
                else {                      
                    e.preventDefault();
                    alert('Dados incorretos!');                     
                }

            }       
    });

and the following html:

<form name="form1" id="form1">
         <input name="nome" type="text" placeholder="Usuário "/> 
         <input name="senha" type="password" placeholder="Senha "/> 
         <input type="submit" value="Login"/>
      </form>

I’m doing a check according to the vector indices users, the problem is: When verifying that the user exists, it will print Dados incorretos until you arrive at the correct index and print the welcome message and make the redirect.

See the example below:

var botao = document.querySelector('input[type="submit"]');

    botao.addEventListener('click', function(e) {
        let form = document.querySelector('form');

        let ipt = {
             nome: form.nome.value,
             senha: form.senha.value                 
        }

        var users = [
          {nome: "Jorge", senha: "123"},
          {nome: "Joao", senha: "joao"},
          {nome: "Maria", senha: "maria"},
          {nome: "José", senha: "jose"},
          {nome: "Ana", senha: "ana"},
        ]

            for(let i = 0; i<users.length; i++) {                           
                if (ipt.nome == users[i].nome && ipt.senha == users[i].senha) {
                    e.preventDefault();
                    console.log('Bem vindo ' + form.nome.value + " !");
                    //window.location.href= "http://www.google.com";                       
                }
                else {                      
                    e.preventDefault();
                    console.log('Dados incorretos!');                     
                }

            }       
    });
<form name="form1" id="form1">
    	     <input name="nome" type="text" value="Ana" placeholder="Usuário "/> 
             <input name="senha" value="ana" type="password" placeholder="Senha "/>	
    		 <input type="submit" value="Login"/>
    	  </form>

See that it prints 4 messages from dados incorretos and only then print the bem vindo.

Can someone help me?

3 answers

1


var b = false

for(let i = 0; i<users.length; i++) {                           
    if (ipt.nome == users[i].nome && ipt.senha == users[i].senha) {
        e.preventDefault();
        console.log('Bem vindo ' + form.nome.value + " !");
        //window.location.href= "http://www.google.com";
        b = true                       
    }
} 

if(b == false) {                      
    e.preventDefault();
    console.log('Dados incorretos!');                     
}

Create a boolean variable false before the for, if in the middle of the loop you find a correct user/password change the variable to true, when it’s over if she’s still there false show the message

for(let i = 0; i<users.length; i++) {                           
    if (ipt.nome == users[i].nome && ipt.senha == users[i].senha) {
        e.preventDefault();
        console.log('Bem vindo ' + form.nome.value + " !");
        //window.location.href= "http://www.google.com";
    } else if(i == users.length - 1) {                      
        e.preventDefault();
        console.log('Dados incorretos!');                     
    }
}

Or in the else within the for also check whether the i is equal to the size of users

  • Yeah, I was doing it that way, I was wondering if there’s any other way to accomplish the implementation than with a check booleana.

  • edited the answer with another solution, it may be that instead of == be it >, forehead there

  • Adding the else if have no effect whatsoever.

  • you must write the else

  • I was wrong: the right thing is } else if(i == users.length - 1) {

0

Use the Array.find to fetch one element in the array, if the element is not found, the return is undefined

search = users.find(user => user.nome==ipt.nome && user.senha==ipt.senha)

if(search){
  e.preventDefault();
  console.log('Bem vindo ' + form.nome.value + " !");
  //window.location.href= "http://www.google.com";
}
else{
  e.preventDefault();
  console.log('Dados incorretos!');   
}

NOTE: I hope you are not making an access control system this way, because anyone can open javascript and see which users/passwords are declared in their variable users

  • No, until pq to perform checks of these types, a language would be required in part of the back-end, I’m only conducting tests.

0

You can use the filter of Javascript, which is a function where you make the comparison of what you are looking for so that it returns a boolean, and can replace the for

var users = [
          {nome: "Jorge", senha: "123"},
          {nome: "Joao", senha: "joao"},
          {nome: "Maria", senha: "maria"},
          {nome: "José", senha: "jose"},
          {nome: "Ana", senha: "ana"},
        ]

var n = 'Joao'; // nome procurado
var s = 'joao'; // senha procurada

var u = users.filter(function(user){ 
    return user.nome == n && user.senha == s; 
});

if (u.length > 0) {
   console.log('Bem-vindo ' + u[0].nome);
} else {
   console.log('Dados incorretos');
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.