var firstNumber = 2; var secondNumber = 10;
Topics to be covered in part 2
Arrays (V) - You’ve already seen variables
var firstNumber = 2; var secondNumber = 10;
Functions (VI) - You’ve already been using "built in" functions:
prompt( "enter a number" ); alert( "Hello World" ); eval( firstNumber + secondNumber );
And, finally:
These notes are available in a few different forms.
The slide show version. This has all the essential information for the module.
An HTML version laid out like a book. This has some additional supplementary material, providing some background. The javascript examples should work directly in this version.
This version is printed for the handouts. It has the same material as the expanded version. Obviously, the javascript examples will not run.
All of these versions are missing some questions and answers which I will uncover during the lectures. These missing parts are marked so you know where they are, and look like this: uncovered .
There are many examples in these slides. These come in three forms.
Good code — if there in an error, it is not intentional!:
alert( "Hello World" );
Broken code — will always be marked, normally, although not always before the error. Broken does not (only) mean "will not run":
// BROKEN alert("Goodbye World");
Bad code — sometimes I won’t be able to explain yet why it is bad:
// BAD -- this is hard to read and performs badly alert( "H" + "e" + "l" + "l" + "o" + " " + "W" + "o" + "r" + "l" + "d" );
If you do not know a value when you write your code, you can use a variable.
For example:
var studentsInRoom = 200 var studentsAwake = 150 var studentsListening = 100
But what if you need to store several values?
One solution would be to create several variables.
var studentOne = "John" var studentTwo = "Paul" var studentThree = "George" var studentFour = "Ringo"
Caution
|
This is not a good solution! |
Another solution would be to put multiple values into a single variable.
var studentNames = "John" + "Paul" + "George" + "Ringo"
Caution
|
This is really not a good solution! |
But, now we can’t get the values back out, so we need a separator.
var studentNames = "John" + ";" + "Paul" + ";" + "George" + ";" + "Ringo"
What is the problem with solution?
If you go shopping, you write a list.
Taken from: http://www.flickr.com/photos/whiskeytango/2098182380/ CC by 2.0
The solution in javascript is much the same; You use an Array.
Before you use an array, you need to make one.
There are two main ways to declare an array
// declare a new array with the new keyword var students = new Array(); // declare a new array with 10 empty elements var students2 = new Array(10); // declare an empty array, using the literal syntax var students3 = []; // declare an array with some initial values var students4 = ["John", "Paul", "George", "Ringo"];
Arrays have a number of properties. Considering this array.
// declare an array var student = ["John", "Paul", "George", "Ringo"]; // we can access the size like this... alert( "Size of array: " + student.length ); // we can access elements like this... alert( "2nd Element of array: " + student[2] );
Iteration means doing something to every element in the list.
You have already seen the for loop.
// a simple for loop in javascript var alertString = ""; for(var i = 0;i < 4; i++){ alertString = alertString + i + "\n"; } alert(alertString);
By combining the counter variable from the for loop, with an array, we can iterate.
// declare an array with some initial values var students = ["John", "Paul", "George", "Ringo"]; var alertString = "Array values are:\n"; for(var i = 0; i < students.length;i++){ alertString = alertString + i + ":" + " " + students[i] + "\n"; } alert(alertString);
You can also put values into an array in the same way:
// declare an array with no initial values var students = new Array( 4 ); // ask the user for values for(var i = 0;i < students.length;i++){ // users count from 1 students[ i ] = prompt( "Please enter student number " + (i + 1) + ":", "" ); } // print the results out -- this is the same code as before. var alertString = "Array values are:\n"; for(var i = 0; i < students.length;i++){ alertString = alertString + i + ":" + " " + students[i] + "\n"; } alert(alertString);
Given an set of student names as an array, how do I find the first one in the alphabet?
Think about this for five minutes.
Finding out which of two strings is earliest in the alphabet is straight-forward.
alert("John" < "Paul"); alert("John" > "Paul");
Now, we need to know how to compare the first two names.
// declare an array with some initial values var students = ["John", "Paul", "George", "Ringo"]; var firstInAlphabet = students[ 0 ]; if( firstInAlphabet > students[ 1 ] ){ firstInAlphabet = students[ 1 ]; } alert( firstInAlphabet );
Finally, we need a loop to finish off.
// declare an array with some initial values var students = ["John", "Paul", "George", "Ringo"]; var firstInAlphabet = students[ 0 ]; for( var i = 1; i < students.length; i++ ){ if( firstInAlphabet > students[ i ] ){ firstInAlphabet = students[ i ]; } } alert( "First in alpabet is: " + firstInAlphabet );
This is an usual loop because it doesn’t start at the beginning of the array; the example still works in this case.
Can you modify this example, so that it asks the users for input first?
What do these loops do?
var students = ["John", "Paul", "George", "Ringo"]; // BROKEN!!! var alertString = "Array values are:\n"; for(var i = 1; i < students.length;i++){ alertString = alertString + i + ":" + " " + students[i] + "\n"; } alert(alertString); // Ok, but wierd alertString = "Array values are:\n"; for(i=1; !(i>students.length); i++){ alertString = alertString + (i-1) + ":" + " " + students[i-1] + "\n"; } alert(alertString); // OK, but different alertString = "Array values are:\n"; for(i = 0; i != students.length;i++){ alertString = alertString + i + ":" + " " + students[i] + "\n"; } alert(alertString);
for loops look easy, but they are very easy to get wrong.
// declare an array with some initial values var students = ["John", "Paul", "George", "Ringo"]; var alertString = "Array values are:\n"; for(i in students){ alertString = alertString + students[i] + "\n"; } alert(alertString);
So, can we see a more real example?
Yes, but the code snippets will get longer. So in future slides, I am going to miss some bits out.
// the line before this is // var alertString = ""; alertString="Hello World"; // the line after this is // alert( alertString );
Here is a slightly more useful example.
// set up the display alertString = "Slides in talk:"; // get a copy of the slides from the browser var slides = w3c_slidy.slides; // collect all the slides in this talk, and count them. for( i in slides ){ alertString = alertString + i + " "; }
This code counts the slides start to finish. How could you achieve the same, but counting backward?
// set up the display alertString = "Slides in talk:"; // get a copy of the slides from the browser var slides = w3c_slidy.slides; // collect all the slides in this talk, and count them. for( i in slides ){ alertString = alertString + i + " "; }
We start with an easier version first.
// declare an array with some initial values var students = ["John", "Paul", "George", "Ringo"]; // set up the display var alertString = "Array values are:\n"; for(var i = students.length - 1; i >= 0;i--){ alertString = alertString + i + ":" + " " + students[i] + "\n"; } alert( alertString ); // set up the display alertString = "Slides in talk:"; // get a copy of the slides from the browser var slides = w3c_slidy.slides; // collect all the slides in this talk, and count them. for(var i = slides.length - 1; i >= 0;i--){ alertString = alertString + i + " "; } alert( alertString )
In this case, we need to use for loop. You may be able to work out how to do this with a for … in loop later in the module.
Like any variable, we can also assign new values to an array element.
// declare an array with some initial values var students = ["John", "Paul", "George", "Ringo"]; var alertString = "Array values are:\n"; for(i in students){ alertString = alertString + students[i] + "\n"; } alert(alertString); // we can change the value with the normal "=" operator. students[ 2 ] = "Georgina"; alertString = "Array values are now:\n"; for(i in students){ alertString = alertString + students[i] + "\n"; } alert(alertString);
An edge case is a problem or situation that occurs only at an extreme (maximum or minimum) operating parameter.
What happens if you add more objects to an array element that doesn’t exist?
var array = new Array( 2 ); alertString = "Before: " + array.length + "\n"; // array indexes start from 0! array[2] = "Broken?"; alertString = alertString + "After: " + array.length;
Javascript copes with this without complaining.
What happens if you access an element that does not exist?
var students = ["John", "Paul", "George", "Ringo"]; // array indexes start with 1! alertString = "Element value is: " + students[ 4 ];
Any array element which has not been explicitly given a value, has an undefined value.
Undefined is a special value in Javascript.
var array = []; alertString = "String Comparison: " if( "undefined" == "undefined" ){ alertString = alertString + "=="; } else{ alertString = alertString + "!="; } alertString = alertString + "\nUndefined Comparison: " if( array[0] == "undefined" ){ alertString = alertString + "=="; } else{ alertString = alertString + "!="; }
// This is BROKEN code to sum the numbers in an array var array = [ 1, 2, 3 ]; var total = 0; for( var i = 0; i <= array.length;i++ ){ total = total + array[ i ]; } alertString = "Total is: " + total;
We will now look at longer example:
Given an array of students, sort them alphabetically.
How might you do this, if the names were written on paper.
We take the same approach, with one minor change.
// declare an array with some initial values var students = ["John", "Paul", "George", "Ringo"]; // you have seen how to print the elements of an array many times, so we take // a short cut here. We will investigate ".join" more later. alert( "Before:\n" + students.join( "\n" ) ); var indexOfEarlist; var temp; // iterate through the array for(var current = 0; current < students.length - 1; current++){ indexOfEarliest = current; // find the earlist in the alphabet of the rest of the array for(var next = current + 1; next < students.length; next++){ if( students[ next ] < students[ indexOfEarliest ] ){ indexOfEarliest = next; } } // now swap them. This may swap a element with itself! temp = students[ current ]; students[ current ] = students[ indexOfEarliest ]; students[ indexOfEarliest ] = temp; } alert( "After:\n" + students.join( "\n" ) );
Originally, we considered the motivation for an array, compared to a variable.
So far, we have considered arrays containing the names of students.
var students = ["John", "Paul", "George", "Ringo" ]; var dob = [ "1940", "1942", "1943", "1940"];
This work till, we want to add other important information.
var gender = ["male", "male", "male", "male"]; var living = [false, true, false, true];
Caution
|
This is not a good solution! |
Another solution!
var students = [ "John:1940:male:dead", "Paul:1942:male:alive", "George:1943:male:dead", "Ringo:1940:male:alive" ];
A two-dimensional array:
var students = [ 4 ]; students[ 0 ] = new Array( 3 ); students[ 0 ][ 0 ] = "John"; students[ 0 ][ 1 ] = "1940"; students[ 0 ][ 2 ] = "Dead"; students[ 1 ] = new Array( 3 ); students[ 1 ][ 0 ] = "Paul"; students[ 1 ][ 1 ] = "1940"; students[ 1 ][ 2 ] = "Alive"; // etc....
Fortunately there is a literal syntax, which is more compact.
var students = [ ["John", "1940", "Dead"], ["Paul", "1942", "Alive"], ["George", "1943", "Dead"], ["Ringo", "1940", "Alive"] ];
How to print this array out?
var students = [ ["John", "1940", "Dead"], ["Paul", "1942", "Alive"], ["George", "1943", "Dead"], ["Ringo", "1940", "Alive"] ]; for( i in students ){ for( j in students[ i ] ){ alertString = alertString + students[ i ][ j ] + "\t"; } alertString = alertString + "\n"; }
This material is copyright by Newcastle University. It is written by Phillip Lord, modified from original lectures by Jennie Palmer.