Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Loop backwards Javascript Array

I would like to loop backwards in a array in javascript and then get the index of each element in the array for example if a array has 10 elements and is looped backwards it would log 9, 8, 7, 6, 5, 4, 3, 2, 1, 0. for some werid reason i am getting a bunch of negaitive -1s and im confused why it wont just return the index properly.

here is the code

//Arrays I would like to pass into the function

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];

function validateCred(arr) {
    let sum = 0;
    for (let i = arr.length - 1; i >= 0; i--) {
        console.log(arr.indexOf(i));
    }
}

console.log(validateCred(valid1));
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

why -1s?

It is because of arr.indexOf(i) when the loop starts i=15 so:

arr.indexOf(15) will return -1 because you don't have a 15 in your array.

next i=14 same as above.

. . .

i=9 then it will find the element at index 3.

about 4 years ago · Juan Pablo Isaza Denunciar

0

As UnholySheep explains above, Array.indexOf(i) gives you the index of the first occurrence of the value represented by i in the array. Here is some code to help you debug:

function validateCred(arr) {
  let sum = 0
  for (let i = arr.length - 1; i >= 0; i--) {
    console.log(i)        // log the index
    console.log(arr[i])   // log the value
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda