1

I've created a random number selecting system but I couldn't figure out how to pick it from the array please help me. Here is my code:

var buttonColours = ["red", "blue", "green", "yellow"];
var randomChosenColour = buttonColours[newSequence];

function newSequence () {
  var randomNumber = Math.floor(Math.random() * 4);
}
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Bati
  • 53
  • 1
  • 8
  • Remember that functions in JavaScript do not return any value *unless* you have an explicit `return` statement. – tadman Jul 24 '20 at 19:45
  • Does this answer your question? [Getting a random value from a JavaScript array](https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array) – Heretic Monkey Jul 24 '20 at 19:49

4 Answers4

2

I have extended your code with a function call and a return statement:

var buttonColours = ["red", "blue", "green", "yellow"];
var randomChosenColour = buttonColours[newSequence()];

function newSequence () {
  var randomNumber = Math.floor(Math.random() * 4);
  
  return randomNumber;
}

console.log(randomChosenColour);

Or see a shorter version based on the suggestion:

const buttonColours = ["red", "blue", "green", "yellow"];
const newSequence = () => Math.floor(Math.random() * 4);
const randomChosenColour = buttonColours[newSequence()];

console.log(randomChosenColour);
norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

You need to call newSequence to generate the number. and return the randomNumber from the function.

Like this:

var buttonColours = ["red", "blue", "green", "yellow"];
var randomChosenColour = buttonColours[newSequence()];

function newSequence () {
  var randomNumber = Math.floor(Math.random() * 4);
  return randomNumber;
}

There were two problems, the index selecting a value was not a number, it was a function (because the function was not being called), and secondly the function was creating a number but not returning it.

Hope this helps!

Aniket Gargya
  • 818
  • 1
  • 11
  • 21
1
var randomColor=buttonColours[Math.floor(Math.random()*4)];

or, leaving room for expansion:

var randomColor=buttonColours[Math.floor(Math.random()*buttonColours.length)];
iAmOren
  • 2,760
  • 2
  • 11
  • 23
0

Really all you need is a function to pick a random value, like _.sample from Lodash:

function sample(arr) {
   return arr[Math.floor(Math.random() * arr.length)];
}

Where that can handle arbitrary arrays of arbitrary length:

sample(buttonColors);

Your newSequence function is way too specific and presumes a lot about the structure of the data. That 4 is a huge liability that needs to be removed.

tadman
  • 208,517
  • 23
  • 234
  • 262