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

202
Vistas
I want to console.log a random array it works when I pass in a number but it doesn't when I directly hard code it in the console.log()

When I do this, the code works.

console.log(characters.data.results[2])

I would obviously get the third object in the array. but this is static. I want it to be randomized so I did this.

console.log(Characters.data.results[Math.floor(Math.random() * 21)])

it didn't work, I keep getting this error

Main.jsx:6 Uncaught TypeError: Cannot read properties of undefined (reading 'results')
at Main (Main.jsx:6:1)
at renderWithHooks (react-dom.development.js:16175:1)

I even made the code cleaner by doing

const random = Math.floor(Math.random() * 21);
console.log(characters.data.results[random])

but I got the same error. What am I doing wrong? I am new to react.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The value of Characters.data is undefined on first render and maybe changing afterwards.

To make sure Characters.data is not undefined before accessing Characters.data.results. You can use optional chaining (?.)

console.log(Characters.data?.results[Math.floor(Math.random() * 21)])
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