// Creating an array of 5 numbers
var nums = new Array(1, 6, 2, 9, -3);
// Creating an array of 5 strings
var names = new Array("Aaron", "Dave", "Angie", "Pat", "Sam");
// Changing the third element of the nums array
// Note: array elements start counting at 0,
// so 2 is the third element
nums[2] = 42;
// Displaying the elements of an array as a list
// Note: This code would have to be run inside the
// body of the HTML page as it is being created.
// This is not considered a good thing to do,
// but works and is less complex for example
// purposes.
document.writeln("<ul>");
for (var i=0; i<nums.length; i++) {
document.writeln("<li>" + nums[i] + "</li>");
}
document.writeln("</ul>");
See arrayDisplay.html for example of above code running.
// Displaying the elements of an array as a series of
// paragraphs right after an element with the id of xxx
// Note: This code would be run after the web page has
// loaded. Note also the similarity in the loop code.
// It is a common design pattern for processing
// arrays.
// Note: This code is contained within a function so it
// can easily be called after the document has been
// loaded.
// Note: The last statement sets an attribute on an element
// because the notes needed to cover that somewhere.
function addParagraphs() {
var elem = document.getElementById("xxx");
for (var i=0; i<names.length; i++) {
// create a paragraph element
var para = document.createElement("p");
// create the text that goes inside the paragraph
var text = document.createTextNode(names[i]);
para.appendChild(text);
// add the paragraph to the main document
elem.appendChild(para);
// set an attribute for the paragraphs
para.setAttribute("style", "font-size:36pt");
}
}
See arrayParas.html for example of above code running.