Arrays

We started learning about arrays. We learned that arrays are lists and that the first item of the list is number 0. We can also have lists inside of lists. Here’s an example.

var passengers = [

[“Lee”, “red”, “grapes”],

[“Dave”, “blue”, “oranges”]

];

This is a list of two things, two people and some information about them. Each person is a list of three things.

passengers[0] would be [“Lee”, “red”, “grapes”].

We can use two numbers to pull out just one piece of that information.

passengers[0][0] would give us “Lee”.

If we write to the html passengers[0][0], it would write Lee, not “Lee.”

What would passengers[1][2] give us? It would give us “oranges”.

We used the method of “push”. I also told you that you could add a space, literally using a + sign. There is a method for that as well.

var list = [0, 1, 2, 3, 4, 5]

list.join(“, “);

That would give us 0, 1, 2, 3, 4, 5. It joins the elements together with whatever you put there. The quotation marks are important in order to get in any spaces you want included. Remember that spaces in your code don’t mean anything. The way I wrote the variable passengers you can do because spaces don’t matter. You could also write that all together.

var passengers = [[“Lee”, “red”, “grapes”], [“Dave”, “blue”, “oranges”]];

Other methods include pop and shift. Pop takes off the last element. Shift takes off the first.

var x = list.pop();

x would equal 5. List would now be [0, 1, 2, 3, 4].

var x = list.shift();

x would equal 0. List would now be [1, 2, 3, 4, 5].

Other methods include delete, unshift, and splice. Splice can take out and add elements.

list.splice(1, 3, 7, 8) would start at element 1, take out three elements from the list and add in 7 and 8. It would give us [0, 4, 5, 7, 8].

list.splice(0, 4) would start at the element at position 0, namely the number 0, and take out 4 elements. That would leave us with [5].

I use splice in some of my activities where I have several questions and when they get it right, the question is spliced out of the list of questions. When they get it wrong, it goes back in to randomly be asked at some point. When the array is empty, then the game or quiz is over.

You can watch the lesson as well.