Tengo esta función simple que escribí que genera un número aleatorio, obtiene el objeto en una matriz en ese índice y luego devuelve ese objeto
function darkHumor(){ let randInt = Math.ceil(Math.random() * jokes.length); let joke = jokes.at(randInt); console.log(randInt); return joke; } El problema es que cuando trato de usar una joke , aparece como indefinido.
<div className="buildUpArea">{joke.buildUp}</div>¿Podría alguien señalar mi error?
Así es como se ve la matriz de chistes si ayuda
const jokes = [ { id: "1", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, { id: "2", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, { id: "3", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, { id: "4", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, { id: "5", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, ] export default jokespuedes hacer algo como esto
Cambié Math.ceil con Math.floor porque quieres un índice entre 0 y longitud - 1
function darkHumor(jokes){ let randInt = Math.floor(Math.random() * jokes.length); let joke = jokes[randInt]; console.log(randInt); return joke; } const jokes = [ { id: "1", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, { id: "2", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, { id: "3", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, { id: "4", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, { id: "5", buildUp: "test build up", punchLine: "test puncline", jokeInfo: "test joke info", infoLink: "test info link", }, ] Array.from({length: 10}).forEach(() => console.log(darkHumor(jokes)))