I'm trying to make a search through three different arrays of strings in Javascript, looking for a name (submitted by user), and if this name is found, I have to return in which array it is located.
Something like that: HTML
let users = ['mario', 'gianni', 'pinotto'];
let admins = ['moana', 'cicciolina', 'selen'];
let mods = ['frodo', 'sam', 'bilbo'];
const form = document.querySelector('form');
const btnNome = document.querySelector('#nome');
let risp = document.querySelector('#risposta');
function search() {
risp.innerText = '';
let nome = btnNome.value.trim();
for (i = 0; i < mods.length; i++) {
if (nome == mods[i]) {
risposta.innerText += `${nome} is a moderator`;
break;
} else if (i == users.length - 1) {
for (i = 0; i < admins.length; i++) {
if (nome == admins[i]) {
risposta.innerText += `${nome} is an admin`;
break;
} else if (i == users.length - 1) {
for (i = 0; i < users.length; i++) {
if (nome == users[i]) {
risposta.innerText += `${nome} is a registered user`;
break;
} else if (i == users.length - 1) {
risposta.innerText += `${nome} NON è registrato`;
break;
}
}
}
}
}
}
form.reset();
};
<form>
<label for="text">Insert name</label>
<input id="name" type="text" name="text" required/>
<input type="button" onClick="search()" value="search">
</form>
BUT it doesn't work, and freezes the browser. I think I have mistaken something creating a infinite loop... any ideas? thanks
THANK you everyone for your answers, which were all very useful.
risposta. Also the variable isrispnotrispostavar,letorconstotherwise they are global. You should go withletin this case to get a writable variable with block scope.some