Arrays
Arrays in JavaScript index data according to natural numbers.
JavaScript arrays can also function as stacks.
A stack is a data structure in which the last element to go in is the
first element to go out.
All arrays in JavaScript support pop
and push
methods.
JavaScript arrays can also function as queues. A queue is a data structure in which the first element in is the first element out.
For loops are frequently used to iterate over the elements of an array:
DOM-tree manipulation
DOM stands for "Document Object Model," and the DOM tree is a
tree-like data-structure that describes the logical
model behind the
document.
If you want to change the appearance of a page, you can modify or add
to the DOM tree.
JavaScript allows you to manipulate the DOM tree using procedures like
document.getElementById
document.appendChild
,
document.createElement
and
document.createTextNode
.
Or, we could have accomplished the same effect with one write to
an innerHTML
property:
Manipulating the DOM tree is considered good style, while innerHTML
is considered poor style.
The advantage to DOM-tree manipulation is that it preserves attributes
that have been applied, while innerHTML wipes them out.
Unless this preservation is actually required, innerHTML
is a perfectly reasonable approach.
Events
Many of the elements on a web page respond to events, including clicking, typing and mousing. When an element has "focus," and an event occurs, the corresponding event handler on that object is invoked. It is possible to attach event handlers to elements in JavaScript:
You can watch a text input field, and update some part of the page instantaneously:
Note that event-handling code can be specified directly in attributes inside HTML.
Below is the beginning of a board-game board built out of tables; click each square to change its color to red:
Exercise: Board Game
Make the game board below "playable." That is, if a user clicks on a cell, and then clicks on another cell, it should move the ship from the old cell to the new cell.
Hint: You may want to use the childNodes
property of an element.