Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
How to check user input for all possible values?

I have written this JavaScript code where I have defined an array and took input from user and then compared the input and value from an array. On successful checking the URL will be concatenated with the correct input of the user but if the user provides wrong input, which is not within the array, then it will execute the else part of the if–else statement. The code is successful until the initialization of i = 0, but then it’s not working for the other values other than the 0th position and always goes to the else part. What am I doing wrong?

var myStringArray = [ "youth", "robinson", "volvo", "bmw" ];
var arrayLength = myStringArray.length;
var url = "https://abcd.com/";
var company = prompt("Input your company Code to login");

for (var i = 0; i < arrayLength; i++) {
  var name = myStringArray[i];
  
  if (name == company) {
    window.open(url.concat(company));
  }
  else {
    alert("Company Code is wrong Try again from login");
  }
  
  break;
}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can only know whether the input is not in the array when you have looked at the whole array. So you should not alert inside the loop, nor break out of it in the first iteration. Only alert when the loop has completed without finding the input.

var myStringArray = ['youth', 'robinson', 'volvo', 'bmw'];
var arrayLength = myStringArray.length;
var url = "https://abcd.com/";
var company = prompt("Input your company Code to login");
for (var i = 0; i < arrayLength; i++) {
  var name = myStringArray[i];
  if (name == company) break;
}
if (name == company) {
  window.open(url.concat(company));
} else {
  alert("Company Code is wrong Try again from login");
}

Note that there are useful methods in JavaScript for this kind of array searching, like includes. Also, it is more common to use the + operator for concatenating strings:

var myStringArray = ['youth', 'robinson', 'volvo', 'bmw'];
var url = "https://abcd.com/";
var company = prompt("Input your company Code to login");
if (myStringArray.includes(company)) {
  window.open(url + company);
} else {
  alert("Company Code is wrong Try again from login");
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You should not break the loop till the loop completes its execution. You should remove the else block logic outside the loop.

What is happening in your case is, when your loop finds a non matching value from the array, the else statement executes and the break statement will be executed immedietly after that. YOu can break the loop when a matching combination is found. Else the loop should continue the execution

Working Fiddle

var myStringArray = ['youth', 'robinson', 'volvo', 'bmw'];
var arrayLength = myStringArray.length;
var url = "https://abcd.com/";
var company = prompt("Input your company Code to login");
let isFound = false;
for (var i = 0; i < arrayLength; i++) {
    var name = myStringArray[i];
    if (name == company) {
        isFound = true;
        window.open(url.concat(company));
        break;
    }
}
if (!isFound) {
    alert("Company Code is wrong Try again from login");
}

You can also make use of Array.find for the same procedure.

var myStringArray = ['youth', 'robinson', 'volvo', 'bmw'];
var url = "https://abcd.com/";
var company = prompt("Input your company Code to login");
let selectedCompany = myStringArray.find(item => item === company);
if (selectedCompany) {
  window.open(url.concat(selectedCompany));
} else {
  alert("Company Code is wrong Try again from login");
}

about 4 years ago · Juan Pablo Isaza Relatório

0

break; makes it jumps out of the loop. You are using break; out of condition, so the for loop stops after the 1st round anyway. All you need is to remove break; or add break; within if or else condition as you need.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda