War Project – Arrays Intro

Arrays and for loops go together like peanut butter and jelly. Arrays are lists. And if you’ve ever written a list in your life, then you know that they are helpful. Arrays are going to be just as helpful.

We are going to use arrays to hold our cards. Your deck of cards could be described as a list of cards. The first card in your pile could be the three of hearts and the second card the queen of clubs, etc. One list will be all the cards. Two of our lists will be the specific cards held in each player’s hand. Another list will be the two cards being played at the moment.

But before any of that, let’s just see what an array is.

We declare an array like any variable. The notation is square brackets. You can declare an empty array and fill in your list later. That would look like this var laterWillFill = []; Below is an array with a list of fruit.

var list = [“apple”, “banana”, “orange”];  //Putting quotes around the fruit shows that they are strings, just a bunch of characters. If there were no quotes around them, the program would look for a variable called apple.

var L = list.length; //This finds the length of our list, a helpful tool!

$(“#practice”).append(list[1]);  //This will write on the screen, what? It writes banana. Why? Because arrays start with 0. Apple is in place 0 in the array. If we want to find and use apple, we have to use 0 like this.

list[0]   //We use square brackets to call up an item from the array. It’s the array variable name, square bracket, the index of the array item we are looking for, and we close the square bracket.

We can use for loops to build an array. Let’s build an array of 52 numbers like the 52 cards we’re going to have.

var fakeCards = [];

The length of fakeCards right now is 0.

for(i=1; i<53; i++){  //This will give us numbers 1 through 52.

fakeCards.push(i);  //Push is another set command, like .length finds the length.

}

Push will put whatever is in the parentheses into the array it’s attached to. So this is putting in the number 1, then number 2, etc.

At this point, the length of fakeCards is 52.

Can you make a for loop that prints out all 52 numbers? Maybe add a space between each using I + “ “.

You can watch this lesson as well.