I have this simple function I wrote that generates a random number, gets the object in an array at that index and then returns that object
function darkHumor(){
let randInt = Math.ceil(Math.random() * jokes.length);
let joke = jokes.at(randInt);
console.log(randInt);
return joke;
}
The problem is when I try to use joke, it comes up as undefined
<div className="buildUpArea">{joke.buildUp}</div>
Could someone please point out my mistake?
This is what the jokes array looks like if it helps
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 jokes
you can do something like this
I changed Math.ceil with Math.floor because you want an index between 0 and length - 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)))