Display an image using two random arrays using javascipt and html

I’m trying to display an image using two arrays that will randomly select a number and suit type for a card game.

I want to concatenate the two arrays so that it will be able to load the image file and then display the file when loaded.

The files for the cards are saved for example like ‘2Clubs.png’

here’s my code:
javascript

crand=Math.ceil(Math.random()*12);
crand1=Math.ceil(Math.random()*12);
crand2=Math.ceil(Math.random()*12);
srand=Math.floor(Math.random()*4);
srand1=Math.floor(Math.random()*4);
srand2=Math.floor(Math.random()*4);

Hcrand=Math.ceil(Math.random()*12);
Hcrand1=Math.ceil(Math.random()*12);
Hcrand2=Math.ceil(Math.random()*12);
Hsrand=Math.floor(Math.random()*4);
Hsrand1=Math.floor(Math.random()*4);
Hsrand2=Math.floor(Math.random()*4);

cards=new Array(13);
cards[0]='2';
cards[1]='3';
cards[2]='4';
cards[3]='5';
cards[4]='6';
cards[5]='7';
cards[6]='8';
cards[7]='9';
cards[8]='10';
cards[9]='Jack';
cards[10]='Queen';
cards[11]='King';
cards[12]='Ace';

suit=new Array(4);
suit[0]='Hearts';
suit[1]='Spades';
suit[2]='Clubs';
suit[3]='Diamonds';


img = document.getElementById('img1');
img.src=cards[crand]+suit[srand]+'.png';

HTML

<img id="img1" src="" width="100" height="100"></img> 

File structure:



EDIT: No need to concatenate the two arrays. What you did is fine: randomly selected a value and a color, then concatenate the two: this gives you the card name. That you can then call by changing the src of your image.


You have to declare your variables with let. For the purpose of this little program, I have created a randomInt() function that randomly returns an integer between 0 and the value given as argument.

Assuming you have your images in the same directory as the HTML page. If not just navigate by using a prefix ../ to get out of the current directory, etc…