Comparison of object attributes within a for loop

Asked

Viewed 115 times

-1

How to compare a single item of an object that has 3 spaces or more? I want to make a system that, every time the login is equal to some that is already stored in some object, appears an alert stating that the login is already registered.

//objeto
function User(login, senha) {
    this.login = login;
    this.senha = senha;
}

lista = new User(3);

//laço para comparação (NÃO SEI SE ESTA CORRETO)
for (var i = 0; i < n; i++) {
    lista[i] = new User();
    lista[i].login = prompt("Digite o " + (i + 1) + "º usuário para cadastro");
    lista[i].senha = prompt("Digite a senha do " + (i + 1) + "º usuário para cadastro");
    for (var j = i+1; j < n; j++) {
        if (lista[i].login == lista[j].login)) {
            alert("Login já cadastrado!");
        }
    }
}

COMPLETE CODE WITH THE PART THAT IS GIVING ERROR IN COMPARING. FOLLOWS BELOW:

/*ENUNCIADO:
Crie Uma lista de usuários(Login e Senha); Mostrar um alerta todas as vezes que o usuários digitar um login igual.*/

function User(login, senha) {
    this.login = login;
    this.senha = senha;
}

//ENTRADA DA QUANTIDADE DE CADASTROS QUE DESEJA FAZER
    var n = prompt("Entre com quanto usuários você gostaria de cadastrar");

//LAÇOS PARA POSSIVEIS ERROS DE DIGITAÇÃO
if (n >= 'a' && n <= 'z' || n >= 'A' && n <= 'Z') {
    alert("ERRO!\nEntre com um número inteiro para o cadastro dos usuários.");
    n = 0;
    var n = prompt("Entre com quanto usuários você gostaria de cadastrar");
} else if (n == "" || n == " ") {
    alert("ERRO!\nO Espaço não pode estar em branco");
    n = 0;
    var n = prompt("Entre com quanto usuários você gostaria de cadastrar");
}

//CRIAÇÃO DE UM ARRAY PARA UTULIZAR COM O ARMAZENAMENTO DE VALORES
lista = new User(n);

//LAÇO PARA ENTRADA DO LOGIN E SENHA DO CADASTRO
for (var i = 0; i < n; i++) {
    lista[i] = new User();
    lista[i].login = prompt("Digite o " + (i + 1) + "º usuário para cadastro");
    while(lista[i]login ==lista[i].login) {
      alert("Login já cadastrado!");
      lista[i].login = null;
    }
    lista[i].senha = prompt("Digite a senha do " + (i + 1) + "º usuário para cadastro");
    }
}

1 answer

1


Regarding your question, a general way to verify the presence of a value x in the attributes of objects stored in a vector, we can use the following expression:

vetor.some(elemento => elemento.atributo === x);

The application of this expression in the specific case follows in the code below. However, first I would like to mention what I consider some problems with the code presented:

  • The expression lista = new User(3) is incorrect, one should create the list using lista = [] and create the objects using new User(login, senha).
  • The value of the variable n is not defined.
  • No function return check prompt(), to which you can return null if you click Cancel. It is also interesting to avoid the entry of empty strings.
  • In the loop for (var j = i+1; j < n; j++), iterations are made of the current position of the vector forward, when the opposite should be done.

Finally, applying the formula and making the corrections of the problems presented, including consistency checks, I got the code below:

function User(login, senha) {
    this.login = login;
    this.senha = senha;
}

let lista = [];
let login, senha;
let n = prompt("Quantos usuários deseja cadastrar?");;

for (var i = 0; i < n; i++)
{
    login = null;
    while(login == null || login == "")
    {
      login = prompt("Digite o " + (i + 1) + "º usuário para cadastro");

      if(lista.some(usuario => usuario.login === login)) {
        alert("Login já cadastrado!");
        login = null;
      }
    }

    do {
      senha = prompt("Digite a senha do " + (i + 1) + "º usuário para cadastro");
    }
    while (senha == null || senha == "");

    lista.push(new User(login, senha));
}
  • Buddy, thanks for the answer. I ran your code here and it all worked out. But there are still some things I could not understand in your code... I will edit my comment and by my complete code, and then explain my doubt.

  • I put my second code that was being implemented before seeing your answer. The question is why create a list like this var lista = []; and not like this lista = new User(n); and after you get into the loop it’s like this lista[i] = new User();. My code is running, I just can’t implement the comparison of objects within the for loop. If you can explain your code I would really appreciate it. Hugs, thank you for your attention. Remember: I’m a beginner in Javascript.

  • @Kayorodrigo The User function (login, password) is an object constructor, which as you defined demand as "login" and "password" parameters. You cannot call this function to build a list, it builds objects of the "User" type. If you want to build a list without using var list = [ ], you can also use the list constructor, which already returns the list with the number of elements you want: var list = Array(3). Only by owning the list will you put the objects you create in it.

Browser other questions tagged

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