-1

I want the computer to randomly choose either 8 or 2. I tried doing (Math.random()*8)+2, it chooses a random number BETWEEN 8 and 2 but I want the computer to randomly choose 8 or 2.

So I tried a different way, and I did this:

if(b==0){
var a = 2;
}
else{
var a = 8;
}

However, it is not working. Is there a more efficient and better way?

Thank you, Paul

Paul10
  • 33
  • 6
  • 1
    Choose a random number of either 0 or 1. 0 maps to 8 and 1 maps to 2. See here https://stackoverflow.com/questions/5915096/get-a-random-item-from-a-javascript-array – Paul Rooney Dec 05 '20 at 04:33

1 Answers1

3

Something like this should do.

function randomSelection(values) {
  return values[Math.floor(Math.random() * values.length)];
}

numbers = [2,8];
randomSelection(numbers);

Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35