So far, we’ve needed a new variable name for each new piece of information we wanted to store. Now we will see how to store and manipulate larger groups of data, organized by Javascript in data structures.
An array is a data structure that can store multiple pieces of information, in order, and with a single variable name. There are two main uses of array:
The array name, together with a non-negative integer can be used to refer to the individual items of data. Let’s start with an example:
The variable cars
is an array containing five strings.
The array is defined like any other variable, except that we use square
brackets []
to denote an array and separate the elements of
an array with commas.
We can access individual items of the list by indexing into the list with squares brackets and an intger value:
Note that the first element of the list corresponds to index 0 and so a list with 5 elements will have valid indices of 0, 1, 2, 3, and 4.
We can also print the entire array just like any other variable:
The items of an array can be treated as variables. You can use the assignment operator to change an item in a array.
If you forget that the list is indexed from 0, or for some other reason try to access an item of the array at an index beyond the end of the list, Javascript will print an error message.
To help avoid this error, you can find out how many items are in an array.
This dot-notation (schools.length
) is new.
We’ll tell you how it works and why in the next few sections.
A array is a way of organizing, or structuring, data that your program will use. We say that an array is a data structure, and we will see many other examples of data structures later in the course. One of the key principles of a data structure is that the data structure allows you to apply operations to some or all of the data in a unified way.
Let’s take an example. You decide to start a new financial data aggregation website. Initially, daily currency are recorded in US Dollars.
var apple = [101.42, 96.30, 96.79, 96.66, 97.13, 99.52, 97.39];
But then next year, based on uncertain politics in the United States, the world decides to move to the Euro as the world’s primary currency. You decide to convert all of your currency data from US Dollars to Euros (and move to Canada). You could convert all of your data this way:
You are doing the same type of operation over and over again. Convert
apple[0]
. Convert apple[1]
. Convert
apple[2]
. And so on. This is tedious with only six data
points. Imagine how tedious it would be with millions of data points.
There is a simpler way to apply the same operation to all elements of an
array.
Let’s look more closely at this for-loop. The
for-loop consists of a header and a body. The header
initializes the counter variable i
, and increments the
counter variable as long as i
is less than the length of
the array. We’ll use i
to index into the array for each
conversion we need to do.
The body of the for-loop contains whatever code we want to execute on each iteration of the for-loop. In our example, this is a single line of code that converts the ith element of the array from dollars to Euros:
apple[i] = apple[i] * rate;
Like a function, the body of the for-loop is enclosed between an open and closed curly brackets {}.
Here is a solution.
Modern web pages change and react based on user actions or changing data. Sometimes, these changes are done on the server: a new set of HTML for displaying the desired data is constructed on the server right before it is sent across to the client. Sometimes, these changes are done on the client side: changes to the HTML or style are handled by the client’s browser. These are sometimes called back-end and front-end approaches to making websites responsive.
Many modern web sites contain both front-end and back-end components. For example, data about user purchases might be stored centrally on a server, and accessing that data will require some work on the back end. But since network communication can be slow, user-interface elements can be made most responsive through Javascript on the front end. Furthermore, although computation can often be performed either on the client or server, the owner of the website must pay for computation on the server; if that computation can be done on the clients own computer, then the web application will scale more cheaply.
We’ll see now how to use Javascript to actively manipulate HTML elements.
Information about HTML elements is stored in something called an object. An object contains several variables; the variables can be accessed using dot-notation. Some of those variables might be references to functions; we call such functions methods. Methods have access to the data in an object (stored in the other variables), and can compute values using those values or change the values.
You might have heard of the concept of object-oriented programming. Objects are a way of packaging related data together neatly. An object can be thought of as a record in a database. For example, you might have an index card for someone named “theDonald” and another for “hillary”. Each card would have vital statistics associated with each candidate:
An empty object with no properties can be created using empty braces
{}
. Properties can then be added to the object using
dot-notation: theDonald.party = "Republican"
. You can think
of the property party
as being a variable that is contained
within the object theDonald
; the dot says to go inside the
object and fetch (or create) the variable party
.
So party
is a property of Trump, and it has a particular
value associated with it, Republican
. Objects typically
have several properties. In our example, each of the two objects has the
properties party
, hairColor
, and
age
.
Debugging note: you can use the JSON.stringify
function
to convert an object to its string representation for printing out. JSON
string representations are also used to send information about objects
across networks, or to save representations of objects to files.
Arrays and strings are themselves special types of objects. That’s
why you can use the .length
property to find out how many
items an array or strings holds.
An object can be thought of as containing variables, which we call properties. Those variables may store numbers, strings, references to other objects, or functions.
It is useful if an object that represents or models a particular type
of data contains references to functions that can act on that data. For
example, imagine if you had an object meant to represent a ball. That
ball object might have properties x
, y
,
vx
, and vy
to represent the location and
velocity of the ball. You might also have a function, draw, that draws
ball objects, and a reference to this function might be within the ball
object itself:
When an object has a property that contains a reference to a function, that function it is called a method.
Why do we need methods? Imagine that you have very many different types of object that you would like to draw. Maybe you have a function that draws a ball, another function that draws a tree, and a third function that draws the entire user interface for the cloud9 web application. If we associate each of these methods with an object, then this helps us keep the methods organized, so that we can quickly find them in the code, and name them in a way that makes sense.
HTML code uses tag pairs to label components of a document. Some components may contain other components; the body of the html may contain a list, which contains list items, which themselves might contain both text and links, for example.
Think about the structure of an HTML document. The outmost tag pair
which contains everything else is probably the
<html> </html>
pair. First, that tag pair
contains both a head
and a body
section. The
head section contains a title, which the body might contain lists of
list items, etc.
We can visualize the document as a tree. Here’s an example from dabrook.org:
We say that the root of the tree is the HTML element. That HTML
element contains the head and body, so they are drawn as branches from
the root. (Computer scientists frequently draw trees upside down, with
the root at the top. It’s just easier.) The body contains two
div
’s, which themselves contain various content.
How can we manipulate an HTML document using Javascript? Javascript objects can be used to store both data and references to certain special functions called methods. The mechanism the browser provides to fetch and work with HTML elements is called the Document Object Model, or DOM, because objects are used to refer to elements. There are two stages:
In the code above,
document.getElementById("second_image")
fetches a reference
to an object that can be used to manipulate the img
element
with an id
of "second_image"
. Since no two
objects share the same id in well written HTML,
document.getElementById
will always give access to just a
single object to work with.
Once we have the object, we just set the width
attribute
of the object to 50, and the browser notices the change and updates how
the page is displayed.
You can insert some arbitrary HTML code into a document. First, you
need an element with an id in the document, and no text between the
tags, to serve as a marker. Grab that element using
document.getElementByID
, and then use the special attribute
innerHTML
to set the HTML text that appears between the
tags.
A span
or a div
is a pretty good choice for
a marker element, since spans and divs aren’t really intended to do
anything but label or partition the document:
Here’s a simple web page:
Write some javascript that creates a table within the div with id “ticker_table”, using the data in the variables in the javascript code provided.