How Can I Chose Random Color From An Array?
Solution 1:
I have extended your code with a function call and a return
statement:
var buttonColours = ["red", "blue", "green", "yellow"];
var randomChosenColour = buttonColours[newSequence()];
functionnewSequence () {
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"];
constnewSequence = () => Math.floor(Math.random() * 4);
const randomChosenColour = buttonColours[newSequence()];
console.log(randomChosenColour);
Solution 2:
var randomColor=buttonColours[Math.floor(Math.random()*4)];
or, leaving room for expansion:
var randomColor=buttonColours[Math.floor(Math.random()*buttonColours.length)];
Solution 3:
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()];
functionnewSequence () {
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!
Solution 4:
Really all you need is a function to pick a random value, like _.sample
from Lodash:
functionsample(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.
Post a Comment for "How Can I Chose Random Color From An Array?"