The JavaScript Diaries: Part 12 - Multiple Array Types | 2 | WebReference

The JavaScript Diaries: Part 12 - Multiple Array Types | 2

[previous] [next]

The JavaScript Diaries: Part 12 - Multiple Array Types

Another way (with a little more coding), is by using a constructor function. We learned how to create these in our previous studies. With the constructor function it's easier to track the data since we can assign names to each element in the array. I'll use our previous example to create a different type of multidimensional array.
function guitar(maker,model,color) {

Let's look at the example above as a refresher on how to create a constructor function:

  1. We used the function reserved word to create a function called guitar.
  2. Next, we assigned parameters to the function: maker, model, and color.
  3. We then assigned those parameters to properties by the same name.
    1. The properties are assigned using the this reserved word. The statement says "use the instance of the parameter contained in this object," e.g.:
      • Create a property called maker, using the parameter maker from this object
      • Create a property called model, using the parameter model from this object
      • Create a property called color, using the parameter color from this object

Next, we'll create a new array to contain our data:

var indivModels = new Array();
  indivModels[0] = new guitar("Gibson", "Les Paul", "Sunburst");
  indivModels[1] = new guitar("Fender", "Stratocaster", "Black");
  indivModels[2] = new guitar("Martin", "D-28", "Mahogany");
  indivModels[3] = new guitar("Takamine", "EG330SC", "Spruce");

Here we created a variable called indivModels and initialized it with a value of a new instance of the Array object. Then we created an array for each of the elements within the original array. These add another "dimension" to the array, hence the term "multidimensional." Each of the new arrays contains three elements.

Finally, we need to retrieve the information. To obtain the maker of a designated guitar, we can use the following method:

var myAcoustic = indivModels[3].maker;
alert("My guitar is made by" + myAcoustic);

We declared a variable named myAcoustic and initialized it with the value of the maker parameter of the fourth element "[3}" of the array named indivModels. Here's another opportunity to retrieve other data, if you wish:

var myAcoustic = indivModels[3].maker;
var myModel = indivModels[3].model;
alert("My guitar is a " + myModel + " made by " + myAcoustic);

[previous] [next]

Created: January 20, 2006