Core JavaScript

Lesson 4 : Arrays

Overview

In this JavaScript video tutorial, we demonstrate basic array usage: accessing elements via the bracket operator. For our illustration, we use three renaissance paintings to fill an array.

Download Code

For this lesson, you will need an HTML file and a JavaScript file like the ones that we created in Lesson 1. We use a different JavaScript file, but our HTML file will be essentially the same, except for the filename and the name of the JavaScript file that it calls. The final code files for this lesson are given below. They can be downloaded by left-clicking the link to the right of the video player above.

Program Output Displayed

Lesson4.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="Lesson4.js"></script>
</body>
</html>

Lesson4.js

var qaTrinity = [];

qaTrinity[0] = new Image();
qaTrinity[0].src = "Creation_Michelangelo_1.jpg"
document.body.appendChild(qaTrinity[0]);

qaTrinity[1] = new Image();
qaTrinity[1].src = "TheDescentOfTheHolyGhost_Titian_2.jpg"
document.body.appendChild(qaTrinity[1]);

qaTrinity[2] = new Image();
qaTrinity[2].src = "TheLastJudgment_Michelangelo_3.jpg"
document.body.appendChild(qaTrinity[2]);

The first line of the above JavaScript code declares a variable and initializes it with an empty array. This sets the data type to be an array. After this line, we have three sets of three lines each that create a new Image object, assign its source to be an jpeg of an Italian Renaissance painting, and add the image to the document so that it is displayed.

Each group of three lines is similar to the code that we used in JavaScript Lesson 3. The primary difference is that we create an image object by using "new Iimage()" instead of creating an image element. However, they are basically th esame thing. Also, we use array entries that are accessed with the bracket operator. The lines where we assigned a new entry to a new Image expand the array to accomodate the new entry; so the array grows from size 0 to 1 to 2 to 3 as the program runs.

 

© 2007–2024 XoaX.net LLC. All rights reserved.