Random choices in a Javascript array

Asked

Viewed 758 times

6

Whoa, guys, I’m new to both stackoverflow and JS!

Next, I’m having trouble making a script that chooses a string within an array I wrote the code as follows:

let choices = ['a', 'b', 'c']
Math.floor(choices)

and returns not a number which is perfectly understandable, since the array values are strings, but as had said I’m new in the world of JS and I don’t know if the Math method is the best for the task, the same script in python would be much simpler:

import random

choices = ['a', 'b', 'c']
random.choice(choises)

I would like to know if you(a) would have any method suggestion in the JS that returns the value as in the code in Pythom. Thanks in advance!

3 answers

10


Could implement as follows:

choices[Math.floor((Math.random() * choices.length))]
  • 1

    Great bro, very simple syntax until it looks like python! Solved my problem worth!

6

Well, the approach to your problem is pretty simple. In JS, I recommend generating a random number from 0 to the size of your array with the.length array, and then accessing a random Dice with that same generated number. Would look like this:

let choices = ['a', 'b', 'c']
let tamanho_array = choices.length
let n_aleatorio = Math.floor(Math.random() * tamanho_array);
let retorno_aleatorio = choices[n_aleatorio]

Thus, the random return variable will have its Random value.

4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.