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

298
Vistas
How can I get rid of error - TypeError: Cannot read property '8' of undefined

The while statement keeps throwing an error (TypeError: Cannot read property '8' of undefined) however the console.log still outputs the result that it's meant to.

 var hold = [];
 for (let i = 0; i < (clothes.length - 1); i++) {
   let count = 0;
   if (hold.length === 0) {
     hold.push(clothes[i]);
   } else {
     console.log(clothes[i][8], hold[count][8]);
     while (clothes[i][8] < hold[count][8]) {
       count++;
     }
     hold.slice(count, 0, clothes[i]);
   }
 }
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

This part of the code increments count beyond the length of hold[]

while (clothes[i][8] < hold[count][8]){
  count ++;
};

stepping through manually:

  • clothes[0] gets added as hold[0] by the "if hold is empty clause"
  • clothes[1] gets compared with hold[0] and is < so count++
  • clothes[1] gets compared with hold[1], but there's no hold[1], so you get the error

Add a clause in the while

while (count < hold.length && clothes[i][8] < hold[count][8]){
  count ++;
};

Note the length check must be first otherwise you still get the same error (there's other ways such as break out of the while). The 2nd part of the && is only valuated if the first part is true.


You have other issues stopping a complete solution:

for (let i = 0; i < (clothes.length - 1); i++){

will loop to the length-1, so if you have 3 elements, you only get two. You need to use either

  • i<clothes.length
  • i<=(clothese.length-1)

and

hold.slice(count, 0, clothes[i]);

is not the syntax for .slice and slice returns a new array, does not change the array in place. This should be

hold.splice(count, 0, clothes[i]);

Giving an updated snippet:

var clothes = [[2],[1],[3]];

var hold = []
for (let i = 0; i < clothes.length; i++) {
  var count = 0;
  if (hold.length === 0) {
    hold.push(clothes[i]);
  } else {
    while (count<hold.length && clothes[i][0] < hold[count][0]) {
      count++;
    };
    if (count == hold.length) {
      hold.push(clothes[i])
    }
    else  {
      hold.splice(count, 0, clothes[i]);
    }
  }
}
console.log(hold.join(","));

about 4 years ago · Santiago Gelvez 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