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

201
Visualizações
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 Respostas
Responde à pergunta

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 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