Our game uses a complicated set up to create an array with a for loop because we are creating cards, each of which has both a number and a suit.
So first, let’s look just at the number.
var cards = [ ]; //declaring the variable cards as an empty array
for (i = 1; i < 14; i++) { //uses the numbers 1 through 13 to represent ace through king
cards.push(i); //adds that card number to the array cards
}
This shows making an array with a for loop. The problem is that it just has the numbers one through thirteen in it. We need ace through king (1 through 13) for each suit.
We need each card to be its own array, a mini list of a number and a suit. The array cards is going to hold this list of mini arrays.
We can use two for loops, one inside the other, to accomplish this. They are called nested for loops.
for (i = 1; i < 14; i++) { //uses the numbers 1 through 13 to represent ace through king
for (k = 1; k < 5; k++) { //uses the numbers 1 through 4 to represent the four suits
j = [i, k]; // creates an array with the card’s number and suit
cards.push(j); //adds that card number to the array cards
}
}
The first time through i = 1. While i = 1, k will equal 1, 2, 3, and finally 4. There will be cards that exist in the cards array for [1,1], [1,2], [1,3], [1,4]. These will come to represent in the game the four aces. Then the code will be done with the inner loop and go back to make i = 2 and it will start over with k = 1, making the four 2 cards, etc.
Practice with this by making arrays with for loops, simple and then more complicated. Try writing to your html myArray[1][0] and see if it is what you expect. Work until your results match your expectation.
You can watch this lesson.