<New code>
//INIT: — define array of objects
var flowerArr =[
{ name: 'rose', color: 'red' }, // flowerArr[ 0 ]
{ name: 'lilac', color: 'lilac' }, // flowerArr[ 1 ]
{ name: 'tiger lily', color: 'orange' }, // flowerArr[ 2 ]
{ name: 'bluebells', color: 'blue' }, // flowerArr[ 3 ]
{ name: 'black-eyed susans', color: 'yellow' } // flowerArr[ 4 ]
];
Storing information in complex ways
We have learned a number of ways of storing information:
-
Numbers, such as:
var numberVariable = 42;
-
Strings, such as:
var stringVariable = "Hello world!";
-
Functions, such as:
var mainProcedure = function () { alert( 'Hello world!' ) }
-
Arrays, such as:
var marxArray = [ "Harpo", "Groucho", "Chico", "Karl" ];
-
Objects, such as:
var chickenObject = { name: "Plucky", taste: "quite good!" };
However, most real data worth processing is complex, and combines many of these together.
These can be combined in many ways: arrays of objects, objects of arrays, arrays of arrays, and so on.
Arrays of objects
Let me give you a simple example using cars in a parking lot. Let's say that I have an object that I use to describe a car:
var myCarObject = {
make: "Toyota",
model: "Yaris",
year: 2007,
colour: "blue"
};
Great, there's one car. But there is more than one car in the lot. There are three! So let's add the others...
var jeremysCarObject = {
make: "Ariel",
model: "Atom",
year: 2008,
colour: "deathly silver"
};
var maysCarObject = {
make: "Rolls-Royce",
model: "Phantom",
year: 1956,
colour: "sterling silver"
};
So let's check that you understand this:
myCarObject.colour | |
---|---|
jeremysCarObject.year | |
maysCarObject.colour | |
jeremysCarObject.make |
An array of objects
Since we have three cars in the parking lot, it would make sense that we would link them together. In fact, we can join them into an array!
var parkingLot = [
{ make: "Toyota", // parkingLot[ 0 ]
model: "Yaris",
year: 2007,
colour: "blue" },
{ make: "Ariel", // parkingLot[ 1 ]
model: "Atom",
year: 2008,
colour: "deathly silver" },
{ make: "Rolls-Royce", // parkingLot[ 2 ]
model: "Phantom",
year: 1956,
colour: "sterling silver" }
];
Now we have an array with three cars inside it, each with their own properties. parkingLot now has a structure like this:
parkingLot | [0] | [1] | [2] |
---|---|---|---|
make: "Toyota", model: "Yaris", year: 2007, colour: "blue" |
make: "Ariel", model: "Atom", year: 2008, colour: "deathly silver" |
make: "Rolls-Royce", model: "Phantom", year: 1956, colour: "sterling silver" |
We now have an array of objects! Let's check to see if you understand this...
What is parkingLot[2].make? | |
---|---|
What is parkingLot[0].year? | |
What is parkingLot[1].model? | |
What is parkingLot[2].year? |