javascript – loops and arrays

22
JavaScript – loops and arrays

Upload: talon-griffith

Post on 31-Dec-2015

131 views

Category:

Documents


3 download

DESCRIPTION

JavaScript – loops and arrays. Arrays as cubbyholes. Array is an ordered collection of data The content in the array is sometimes known as the array elements You reference an array using its index. So if there are 10 cubbyholes in the array, it is index from 0 to 9. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: JavaScript – loops and arrays

JavaScript – loops and arrays

Page 2: JavaScript – loops and arrays

Arrays as cubbyholes

Array is an ordered collection of dataThe content in the array is sometimes known

as the array elementsYou reference an array using its index. So if

there are 10 cubbyholes in the array, it is index from 0 to 9.

Page 3: JavaScript – loops and arrays

Create an Array – declaration

In order for you to use an array, you need to declare an array. You need to know prior to declaration, what size you want ie. how many cubbie-holes you want in this array.

var sampleArray = new Array(7) or

var daysOfWeek = new Array(7)

Page 4: JavaScript – loops and arrays

Putting values in cubbie-holes.

var daysOfWeek = new Array(7) /* declaration */

daysOfWeek[0] = "Mon";

daysOfWeek[1] = "Tue";

daysOfWeek[2] = "Wed";

daysOfWeek[3] = "Thu";

daysOfWeek[4] = "Fri";

daysOfWeek[5] = "Sat";

daysOfWeek[6] = "Sun";

/* declaration and initial assignment */

var daysOfWeek = new Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

Page 5: JavaScript – loops and arrays

Loops (remember VB) – for, while The syntax for loops are:for (i=0; i<7; i+=) {

// instructions here }

For example to flash message box of the days:for (i=0; i<7; i++) {

alert("Today is "+ daysOfWeek[i]);}

Or you could take one more step and do the following instead:for (i=0; i<7; i++) {

showDay = daysofWeek[i];alert("Today is "+ showDay); /* you are more comfortable this way */

}

For example to initialize an array to all 0s:var sampleArray = new Array(7);for (i=0; i<7; i++) {

sampleArray[i]=0;}

Page 6: JavaScript – loops and arrays

Loops – for, while

The syntax for while loops is

while (count<7) {

// instructions here

count++; // increment count

}

The syntax for do while loops is

do {

// instructions here

count++; // increment count

} while (count<7)

Page 7: JavaScript – loops and arrays

elements[n]

In the POP/TART exercise when we reset the “values” for the button, we physically go to each button ie. b1.value= "" and b2.value= "" and so on.

There is an easy way using arrays. When a form is loaded on the browser, an element array was

created (without telling you) in the background. So instead of referencing it by its name ie. b1.value, you can use the generic reference array: elements[n].value where n is a number from 0 onwards depending on the order of how the element is arranged. So the the first element would be document.formName.elements[0].value and the next one

would be document.formName.elements[1].value and so on.

Page 8: JavaScript – loops and arrays

Example using element[ ]

While you reset the buttons, you might want to use a “for” loop to reset the values;

document.simpleForm.elements[i].value= "";

However, if you are not sure which element index goes with which GUI, you might want to just simply do this

document.simpleForm.elements[i].value=i;

(for i=0, i < n, i++) where n is the number of GUI objects (buttons, input text, message, labels etc) that you created.

Once you know which index goes with which object, you can now perform a for loop to “reset” the values of the buttons and labels.

Page 9: JavaScript – loops and arrays

Illustration of element[]

d o c ument

fo rm_ ID1

gui_ ID1e lements[0]

gui_ ID2e lements[1]

fo rm_ ID2

gui_ ID3e lements[5]

gui_ ID5e lements[4]

gui_ ID4e lements[3]

gui_ ID3e lements[2]

Page 10: JavaScript – loops and arrays

Pull-down menu with button

<SCRIPT LANGUAGE=JavaScript>function change(){

var i=document.colorform.colormenu.selectedIndex;document.bgColor=document.colorform.colormenu.options[i].value;

}//</SCRIPT><form name="colorform"> <p><select name="colormenu"> < option value ="#777777">flint < option value ="#7465DC">violet dusk < option value ="#2F8B20">clover < option value ="#DA456B">carnation <option value="#FFCCCC">subtle pink </select> <input type=button name= "updateButton" value="Update Color“ onclick="change()"></form>

Page 11: JavaScript – loops and arrays

Pull-down menu without button

<FORM name="colorform" > <P><SELECT NAME="colormenu" onchange="change()" > <OPTION VALUE="#777777">flint <OPTION VALUE="#7465DC">violet dusk <OPTION VALUE="#2F8B20">clover <OPTION VALUE="#DA456B">carnation <OPTION VALUE="#FFCCCC">subtle pink </SELECT> <INPUT TYPE=button VALUE="Update Color" onclick="change()"></FORM>

This is new

Page 12: JavaScript – loops and arrays

Exercise: jex9.html

Using the code from the previous two examples. Create the following page. Make sure you name the two menu with different names. (WARNING: DO NOT JUST COPY AND PASTE WITHOUT KNOWING THIS)

Page 13: JavaScript – loops and arrays

Image Object and images[] array

Using <img src= "abc.gif" > allows us to display images on webpages. What if we want more control of what to show?

When a webpage with images is loaded by a browser, an images[] array is created. The first image is loaded onto images[0] and so on.

Unlike, GUI such as buttons etc, where they are the properties of the FORM, images are properties of the DOCUMENT.

In order to display an image using javascript. The command is straight forward as such.

document.images[0].src= "abc.gif"

Page 14: JavaScript – loops and arrays

Object Hierarchy for images

d o c ument

Ima ge s[0].src

Ima ge s[1].src

Ima ge s[2].src

Ima ge s[3].src

Page 15: JavaScript – loops and arrays

Simple Example

<script language=JavaScript>

function changeCreate() { document.images[0].src="create.gif"}

function changeImpact() { document.images[0].src="impact.gif"}

function changeDrive() { document.images[0].src="drive.gif"}

function changeDiscover() { document.images[0].src="discover.gif"}</script>

<BODY>

<IMG src="create.gif"><FORM><INPUT type=button value="CREATE"

onclick="changeCreate()">

<INPUT type=button value="IMPACT" onclick="changeImpact()">

<INPUT type=button value="DRIVE" onclick="changeDrive()">

<INPUT type=button value="DISCOVER" onclick="changeDiscover()">

</form></BODY>

Page 16: JavaScript – loops and arrays
Page 17: JavaScript – loops and arrays

Pre-loading of images to arrays

You can pre-load your image into arrays and when you need a particular image, you can assign

First a new array has to be declared:

myPic = new Array(); Then you need to write a loop to define or construct the image

object for each array elementfor (i=0; i<n; i++) {

myPic[i] = new Image(); // make sure Image is ‘I’}

Note that n is the number of pictures you like to pre-load. You can then define

myPic[0].src = "pic1.gif";myPic[1].src = "pic2.gif";

Page 18: JavaScript – loops and arrays

Simple Example - revised:jex10.html

<script language=JavaScript>

// declare arrayvar myPic=new Array();

//declare image objects for each array

for (i=0; i<4;i++) {myPic[i]=new Image();

}

// preload the picturesmyPic[0].src="create.gif"myPic[1].src="impact.gif"myPic[2].src="drive.gif"myPic[3].src="discover.gif"

function changeCreate() { document.images[0].src=myPic[0].src;}

function changeImpact() { document.images[0].src=myPic[1].src;}

function changeDrive() { document.images[0].src=myPic[2].src;}

function changeDiscover() { document.images[0].src=myPic[3].src;}</script>

<BODY> same as before ….

Page 19: JavaScript – loops and arrays

The onload event handler

The onload handler says that when the browser loads the page, you can execute the javaScript function immediately

Page 20: JavaScript – loops and arrays

Example of onload handler

function disFirst() {// load the first image in my arraydocument.images[0].src=myPic[0].src;

}

<BODY onload="disFirst()"><IMG src=""><FORM><INPUT type=button value="CREATE" onclick="changeCreate()"><INPUT type=button value="IMPACT" onclick="changeImpact()"><INPUT type=button value="DRIVE" onclick="changeDrive()"><INPUT type=button value="DISCOVER" onclick="changeDiscover()"</form></BODY>

Here is displaying an image using a <IMG SRC .. > command even thoughThe image file name is “”

Page 21: JavaScript – loops and arrays

Small exercise: random picture: jex11.htmlYou will create a similar webpage, except that

the first image that is pre-loaded will not be fixed. Previously it was set to myPic[0].src

Use the Math.random() function that returns 0..1. So if you want a number between 0 to 3 (for 4 pictures). You will do the followingk=Math.round(Math.random()*3);

Now that you have the index k, you can apply to myPic[k].src to get a random picture.

Page 22: JavaScript – loops and arrays

Assignment 2 due soon!

Lesson Learnt: All of us will be spiderman or spiderwoman at the end of the semester.