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

146
Visualizações
Creating a function to search for a value in an array and return it's position index using a loop

I'm very new to JavaScript. I'm trying to create a function that can two take two arguments, an array and a value. The function should return the index where the value is found but ff the value is not found, it should return -1. I want to this using a loop and not a method like for example indexOf.

So this is what I got by now:

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    } else {
      return -1;
    }
  }
}

For some reason it keeps returning -1 even if the value if found. What am I doing wrong?

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

0

In the first time your if happen you return no matter what!

If arr[i] == value you return the index, else - you return -1.

What you want to do is return -1 in the case that none of the array elements is found.

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    }
  }
  return -1;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Your logic is wrong here. First, you return -1 when the function fails to search the right value. Thus, the function is paused and no longer executing. You can learn more about the return statement at MDN. To solve this problem, you need to put the return statement outside the loop. Here is the working code:

<script>
function getIndex(arr, value){
for(let i =0; i<arr.length; i++){
if(arr[i] === value){
return i;
}
}
return -1;
}
document.write(getIndex([1,2,3,4], 21));
</script>

The reason why this piece of code works is because when the value is found, it returns the positions where the value is. Thus, terminates the function. But if it is not, the loop will go forever until I is less than arr.length. Once I is less than arr.length, the loop is done and the return statement is executed.

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