0

I'm fairly new to HTML and I'm able to successfully generate the random numbers, but I want to attach an image to a specific number E.G a card game (11 =jack =12=queen ..etc)

This is what I have

function numbers() {
    var x = Math.floor((Math.random() * 10) + 1);
    var img = document.createElement("img");
    if(x ==1||2||3||4||5||6||7) {
        img.src = "ace.jpg";
    }
    document.getElementById("num").innerHTML = "Rule " + x;
}
j08691
  • 204,283
  • 31
  • 260
  • 272
  • `if(x == 1 || x == 2|| x == 3|| x == 4|| x == 5|| x == 6|| x == 7) {` This would do it, you have to check every single value. – alexandreferris Jun 29 '15 at 19:04
  • possible duplicate of [Concise way to compare against multiple values](http://stackoverflow.com/questions/13737091/concise-way-to-compare-against-multiple-values) – Peter O. Jun 29 '15 at 19:08

2 Answers2

1

You could use switch...case. something like

switch(x) {
case 1:
    img.src = "king.jpg";
    break;
case 2:
    img.src = "queen.jpg"
    break;
...
default:
    img.src = "ace.jpg"

}

where the "..." is just replaced by more cases (how many you need).

the default case is run when no other cases match x.

If you were interested in why the break keyword is necessary, information about it can be found in the link i provided. basically

When the JavaScript code interpreter reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

meaning the whole switch(x){...} is a "block" where x is compared to each case. If there is a match, the code there is executed, but if theres nothing telling it to stop, it'll just keep running code! So the break keyword exits the whole block, keeping other cases from running!

Olivier Poulin
  • 1,778
  • 8
  • 15
  • this introduces the `break` keyword, which is hardly intuitive to someone just learning to program (especially combined with the "fall-through" behavior of a `switch`), but it is still the best way to solve this problem, so +1. – Woodrow Barlow Jun 29 '15 at 19:08
0
imgArr = ['jack.png', 'queen.png','tree.png','man.png','ace.png','king.png','yellow.png','green.png','black.png','white.png'],
      randomNumber = 0,
      numImgMap = {}; // map between image and random number.

function randomNumberGenerator(){
 return Math.floor((Math.random() * 10) + 1);
}

for(var k = 0; k < 10; k++ ){
   randomNumber = randomNumberGenerator();
   numImgMap[randomNumber] = imgArr[randomNumber];

} 
// numImgMap is now your map(object) with random number associated with random images.
Anshul
  • 9,312
  • 11
  • 57
  • 74