I have tried to select random thing from an array but it doesn’t work. Any advice?
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}
var colours = [
[“blue”, “green”, “red”],
]
var i = randomRange(1,3);
function randomColours() {
if(i == 1){
console.log(colours[0]);
} if(i == 2){
console.log(colours[1]);
} else {
console.log(colours[2]);
}
}
randomColours();
the output is
[ ‘blue’, ‘green’, ‘red’ ]
You are approaching the problem in a wrong way I think.
First try to use array.length as your max value.
Second you can get rid of all the if statement in the randomColor function if you work directly with array indexes starting from zero.
Third the randomRange function seems completely wrong to me.
Try to substitute the variables in that function with actual values (i.e. 1 and 3) and calculate the result manually, you should see where the error is.
ah okey I have fixed it
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}
var colours =
[“blue”, “green”, “red”];
var i = randomRange(1,3);
function randomColours() {
if(i == 1){
console.log(colours[0]);
} if(i == 2){
console.log(colours[1]);
} if(i == 3) {
console.log(colours[2]);
}
}
randomColours();
and by the .length you mean like this?
const colours = [“blue”, “green”, “red”,];
const random = Math.floor(Math.random() * colours.length);