You can get a random element from an array in JavaScript using the Math.random()
method and array indexing. Here's an example:
index.tsx171 chars6 lines
In the code above, Math.random()
generates a random decimal number between 0 and 1. We multiply this number by the length of the array to get a random index within the range of the array. We use Math.floor()
to round down the resulting decimal number to the nearest integer, which ensures that the index is within the bounds of the array.
Finally, we use the random index to access a random element from the array and assign it to randomElement
.
gistlibby LogSnag