I have some Javascript that selects a random number between 1 and 10, and then loads one of two images into img.src = based on whether the random number chosen was above 5.
This is my code:
if ((Math.random() * 10) + 1 > 5) {
img.src = '1.jpg';
} else {
img.src = '2.jpg';
}
This works perfectly for 2 images, however I now want it to choose from 4 images.
I tried doing a nested if statement with the above code but I realised I was running multiple instances of Math.random, which defeated the purpose.
So then I tried to define a variable at the start using Math.random, and then wrote a nested If statement as follows:
var picnumber = Math.floor((Math.random() * 4) + 1);
if (picnumber = 1){
img.src = '1.jpg';
} else {
if (picnumber = 2){
img.src = '2.jpg';
}
else {
if (picnumber = 3){
img.src = '3.jpg';
}
else {
img.src = '4.jpg';
}
}}
I’ve run this code over 20 times and it keeps loading the same image, image “1.jpg”. I think I’m doing something very basic wrong here, how can I ensure that the var picnumber will get assigned a random number (either 1, 2, 3 or 4), and that the correct image will be attached to img.src? (I want each image to have a 25% chance of being chosen).
Thanks in advance for your time!
var num = Math.floor(Math.random() * 4 + 1); img.src = num + ".jpg";. Keep the parts separate; a lookup or if can be applied trivially as needed. In any case the "problem" has nothing to do with random but has to do with=(assignment) vs==(equality compare).