cnit 133 interactive web pags – javascript and ajax arrays

45
CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Upload: paula-lewis

Post on 01-Jan-2016

235 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

CNIT 133 Interactive Web Pags –JavaScript and AJAX

Arrays

Page 2: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Agenda

• My Web Site: http://fog.ccsf.edu/~hyip (download syllabus, class notes).

• Arrays.• Array Elements (reading, writing, adding, deleting).• Array length property.• for Loop and Arrays.• Associative Arrays.• Multidimensional Arrays.• Arrays Methods.

Page 3: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Arrays• An array is an ordered collection of values• Each value is called an element, and each element has a

numeric position in the array, known as its index• JavaScript is an untyped language, an element of an array

may be of any type, and different elements of the same array may be of different types.

• Array elements may even contain other arrays, which allows you to create data structures that are arrays of arrays.

• An array is also an object. A typeof operator applied to an array value, it returns the string “object”.

• Arrays are particularly useful for storing data that are somehow related to each other, such as student names, phone numbers, etc.

• JS always begins numbering array elements at zero

Page 4: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Arrays (continue…)• There are three ways to declare an array.

With new operatorvar cups = new Array();var cups = new Array(8); // 8 elements

NOTE: expected size only, can only put size at declare time, allow to add elements to this array dynamically.

With dense array, declare and initialize at the same timevar days = new Array("Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat");var months = new Array("January", "February", "March", "April", "May",

"June", "July", "August", "September", "October", "November", "December"); With array literal (easy way)

var weekendDays = ["Friday", "Saturday", "Sunday"];

• Note: var cups = new Array(); and var cups = []; are the same with empty array.

• NOTE: cups = new Array(1, 2, , 4); // for loop cannot display all data.• NOTE: cups = [1,2, , 4]; // for loop is ok to display all data.

Page 5: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Arrays (continue…)• The easiest way to create an array is with an array literal, which is simply a comma-separated

list of array elements within square brackets:var empty = [ ];var primes = [2, 3, 5, 7, 11];var misc = [1.1, true, "a"];

• The values in an array literal need not be constants; they may be arbitrary expressions:var base = 1024;var table = [base, base + 1, base + 2, base +3];

• Another way to create an array is with the Array( ) constructor in three distinct ways:• Call it with no arguments:

var a = new Array( ); // creates an empty arrayvar a = [ ]; // same as above

• Explicitly specify values for the first n elements of an array:var a = new Array (5, 4, 3, 2, 1, "testing");

• Call it with a single numeric argument, which specifies a length:var a = new Array(10); // creates an array with 10 elements

Page 6: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Reading and Writing Array Elements

• You access an element of an array using the [ ] operator

• You can use this syntax to both read and write the value of an element of an array:

value = a[0];a[1] = 3.14;i = 2;a[i] = 3;a[i + 1] = "hello";a[a[i]] = a[0];

• In JavaScript, the first element of an array is at index 0.

Page 7: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Adding New Elements to an Array• In JavaScript, an array can have any number of elements, and

you can change the number of elements at any time.• To add a new element to an array, simply assign a value to it:

a[10] = 10;• Arrays in JavaScript may be sparse. Array indexes need not fall

into a contiguous range of numbers; a JavaScript implementation may allocate memory only for those array elements that are actually stored in the array:

a[0] = 1;a[10000] = "this is element 10,000";// JavaScript allocates memory only for array indexes 0 and 10000.

Page 8: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Deleting Array Elements

• The delete operator sets an array element to the undefined value, but the element itself continues to exist.

• To actually delete an element, so that all elements above it are shifted down to lower indexes, you must use an array method (Array.shift(), Array.pop(), and Array.splice()).

Page 9: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array length property• All arrays, whether created with the Array() constructor or defined with

an array literal, have a special length property that specifies how many elements the array contains.

• More precisely, since arrays can have undefined elements, the length property is always one larger than the largest element number in the array.

• The length property is automatically updated.var a = new Array(); //a.length == 0, no elements defineda = new Array(10); //a.length == 10, empty elements 0-9 defineda = new Array(1,2,3); //a.length == 3, elements 0-2 defineda = [4,5]; //a.length == 2, element 0 & 1 defineda[5] = -1; //a.length == 6, elements 0,1 and 5 defineda[49] = 0; //a.length == 50, elements 0,1,5, and 49 defined

Page 10: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Iterating Through Arrays• The most common use of the length property of an array

is to allow you to loop through the elements of an array:var fruits = ["mango", "banana", "cherry", "pear"];for (var i = 0; i < fruits.length; i++) {

alert(fruits[i]);}

• This example assumes, elements of the array are contiguous and begin at element 0. If this is not the case, you should test that each array element is defined before using it:

for (var i = 0; i < fruits.length; i++) {if (fruits[i]) {

alert(fruits[i]);}

}

Page 11: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

for Loop and Arrays<html><head><title>Array</title><script language="JavaScript" type="text/javascript">var cups = new Array("Lemonade", "iced tea", "Pepsi");</script></head><body><h1>Array</h1><script language="JavaScript" type="text/javascript">var i;for (i = 0; i < cups.length; i++) {

document.write(i, ". ", cups[i], "<br>");}</script></body></html>

Page 12: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Using Placeholders in an array literal

• Uninitialized element’s value is undefined.• We declared the second array element by using a comma

placeholder in our array literal (see next page sample).• Since we did not provide an initializing value, its value is

undefined. (similar to declaring a variable without initializing it). • NOTE: all browsers seem to handle comma placeholders in the

middle of an array literal the same.• However, Netscape, IE, and Opera handle extra comma listed at

the end of an array differently. • Netscape create empty elements for each comma at the end of

the array, but does not assume an additional element after the last comma

• IE and Opera create empty elements for each comma, plus one to follow the last comma.

Page 13: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Using Placeholders in an array literal sample

<html><head><title>Array placeholder</title><script language="JavaScript" type="text/javascript">var cups = ["Lemonade", , "Pepsi"];</script></head><body><h1>Array placeholder</h1><script language="JavaScript" type="text/javascript">var i;for (i = 0; i < cups.length; i++) {

document.write(i, ". ", cups[i], "<br>");}</script></body></html>

Page 14: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Empty elements at the end of an array literal

<html><head><title>Array empty element at end</title><script language="JavaScript" type="text/javascript"> var cups = ["Lemonade", "Ice tea", "Pepsi", , , ];</script></head><body><h1>Array placeholder at the end</h1><script language="JavaScript" type="text/javascript">var i;

for (i = 0; i < cups.length; i++) {document.write(i, ". ", cups[i], "<br>");

}</script></body></html>

Page 15: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Empty elements at the end of an array literal result

• Result of Netscape0. Lemonade1. Ice tea2. Pepsi3. undefined4. undefined

• Result of IE and Opera0. Lemonade1. Ice tea2. Pepsi3. undefined4. undefined5. undefined

Page 16: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Truncating and Enlarging Arrays

• The length property of an array is a read/write value.

• If you set length to a value smaller than its current value, the array is truncated to the new length; any elements that no longer fit are discarded, and their values are lost.

• If you make length larger than its current value, new, undefined elements are added at the end of the array to increase it to the newly specified size.

Page 17: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Associative Arrays

• Array elements can also be indexed by their names, if a name has been defined. An array indexed by a word, rather than by an ordinal number, is called associative array.

• Support for associate arrays is a nice feature of JavaScript.

Page 18: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Associative Arrays sample<body>

<img src="products.gif" name="products"><img src="services.gif" name="services"><img src="contact.gif" name="contact"><img src="home.gif" name="home">

</body><script>document.images[0] // same as document.images["products"]document.images[1] // same as document.images["services"]document.images[2] // same as document.images["contact"]document.images[3] // same as document.images["home"]</script>

Page 19: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Associative Arrays sample (continue…)

var birthdays = new Array();birthdays["Tim"] = "May 15";Birthdays["Mom"] = "Mar 22";birthdays["Jean"] = "Feb 18";birthdays["Paul"] = "Jan 25";

document.write("Tim\’s birthday is ", birthdays["Tim"], "<br>");

Page 20: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Dynamic Array length in JSvar colors = ["white", "blue", "red"];document.write("colors length: ", colors.length, "<br>"); // 3colors[7] = "pink";document.write("colors length: ", colors.length, "<br>"); // 8

Page 21: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Dynamic Array length in JS sample<html><head><title>Array dynamic length</title><script language="JavaScript" type="text/javascript">

var colors = ["white", "blue", "red"];</script></head><body><h1>Dynamic Array length</h1><script language="JavaScript" type="text/javascript">var i;document.write("colors length: ", colors.length, "<br>");document.write("colors contents: <br>");for (i = 0; i < colors.length; i++) {

document.write(i, ". ", colors[i], "<br>");}colors[7] = "pink";document.write("colors length: ", colors.length, "<br>");document.write("colors contents: <br>");for (i = 0; i < colors.length; i++) {

document.write(i, ". ", colors[i], "<br>");}</script></body></html>

Page 22: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Dynamic Array length in JS resultcolors length: 3colors contents: 0. white1. blue2. redcolors length: 8colors contents: 0. white1. blue2. red3. undefined4. undefined5. undefined6. undefined7. pink

Page 23: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Multidimensional Arrays• JavaScript does not support true multidimensional arrays, but it does

allow you to approximate them quite nicely with arrays of arrays.• To access a data element in an array of arrays, simply use the [ ] operator

twice.• Create a multidimensional array:

var table = new Array(10); // 10 rows of the table for (var i = 0; i < table.length; i++) {

table[i] = new Array(10); // each row has 10 columns}

• Initialize a multidimensional array:for (var row = 0; row < table.length; row++) {

for (var col = 0; col < table[row].length; col++) {table[row][col] = row * col;

}}

• Use the multidimensional array to compute 5 * 7var product = table[5][7]; // 35

Page 24: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Methods• In addition to the [ ] operator, arrays can be manipulated through various

methods provided by the Array class.• join()• reverse()• sort()• concat()• slice()• splice()• push() and pop()• unshift() and shift()• toString() and toLocaleString()

Page 25: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – toString()

• arrayName.toString(), this method joins the elements of an array together and returns the resulting string.

• Every object in JS has a toString() method.• An object’s toString() method is automatically

called whenever you try to represent the object as text or concatenate it to text.

• NOTE: use the toString() method to quickly show the contents of the array.

Page 26: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – toString() sample<html><head><title>Array toString</title></head><body><h1>Array method – toString()</h1><script language="JavaScript" type="text/javascript">var cups = ["Lemonade", "Ice Tea" , "Pepsi"];document.write("Using cups: ", cups, "<br>");document.write("Using cups.toString(): ", cups.toString(), "<br>");var myCups = cups.toString();document.write("Using myCups or myCups.toString(): ", myCups.toString(), "<br>");</script></body></html>

Page 27: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – concat()• arrayName.concat(arrayToadd1[, arrayToadd2, arrayToadd3,…])• Combine two or more arrays together into one, i.e., to concatenate one or

more arrays on to the end of another array.• It does not change the content of the original arrays.

var oldFriends = ["David", "Jane", "Paul"];var newFriends = ["April", "Peter"];var partyInvites = oldFriends.concat(newFriends);// partyInvites is an array with data from oldFriends and newFriends, use for/loop

to get the datapartyInvites = oldFriends + newFriends;// partyInvites is a string with strings from oldFriends + newFriends, cannot use

for/loop to get the data

Page 28: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – concat() sample<html><head><title>Array concat</title></head><body><h1>Array method – concat()</h1><script language="JavaScript" type="text/javascript">var i;var oldFriends = ["David", "Jane", "Paul"];var newFriends = ["April", "Peter"];var partyInvites = oldFriends.concat(newFriends);document.write("oldFriends toString: ", oldFriends, "<br>");document.write("newFriends toString: ", newFriends, "<br>");document.write("partyInvites toString: ", partyInvites, "<br>");document.write("partyInvites for/loop: ", "<br>");for (i = 0; i < partyInvites.length; i++) {

document.write(i, ". ", partyInvites[i], "<br>");}var str_partyInvites = oldFriends + newFriends;document.write("str_partyInvites toString: ", str_partyInvites, "<br>");

document.write("str_partyInvites for/loop: ", "<br>");for (i = 0; i < str_partyInvites.length; i++) {

document.write(i, ". ", str_partyInvites[i], "<br>");}document.write("str_partyInvites has 26 undefined, the size of the string");</script></body></html>

Page 29: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – join()

• arrayName.join([separator])• The join method is similar to the toString() method.• The main difference is that the join method allows

you to optionally specify the delimiter or separator you want to appear between elements.

• If no separator is specified, the array elements are separated by a comma.

• One common use of the join method is to create a string of an array’s contents by assigning the result of the join operation to a variable.

Page 30: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – join() sample<html><head><title>Array join</title></head><body><h1>Array method – join()</h1><script language="JavaScript" type="text/javascript">var oldFriends = ["David", "Jane", "Paul"];

document.write("oldFriends.join(\" \"): ", oldFriends.join(" "), "<br>");document.write("oldFriends.join(\" and \"): ", oldFriends.join(" and "), "<br>");document.write("oldFriends.join(): ", oldFriends.join(), "<br>");

document.write("Program end");</script></body></html>

Page 31: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – reverse()

• arrayName.reverse()• This method reverses the order of the

elements in an array.• NOTE: BE CAREFUL, it actually modifies the

array itself.

Page 32: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – reverse() sample<html><head><title>Array reverse</title></head><body><h1>Array method – reverse()</h1><script language="JavaScript" type="text/javascript">var oldFriends = ["David", "Jane", "Paul"];document.write("oldFriends originally: ", oldFriends, "<br>");oldFriends.reverse();document.write("oldFriends.reverse(): ", oldFriends, "<br>");

document.write("Program end");</script></body></html>

Page 33: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – sort()• arrayName.sort([compareFunction])• By default, this method sorts the elements of an

array alphabetically (Lexicographically) if no compare function is specified. (compare as strings).

• Note: this method permanently changes the order of the array.

• To sort in alphabetically and in descending order:myArray.sort();myArray.reverse();

Page 34: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – sort() (continue…)• To sort in numerical order, you need to provide a user-

defined compare function.• To sort in numerical ascending order:

arrayName.sort(compareFun1);

function compareFun1(a, b) { return a - b;}

• To sort in numerical descending order:arrayName.sort(compareFun2);

function compareFun2(a, b) { return b - a;

}

Page 35: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – sort() sample<html><head><title>Array sort</title></head><body><h1>Array method – sort()</h1><script language="JavaScript" type="text/javascript">var mixArray = ["hi", "Hi" , "HI", -1.5, 9, 700.5, 700, 1, -1];var numArray = [9.75, -4, 1, 7.5, 3, 2, 9, -4.25, 11, 3, 8, 900];var ascArray=[10,20,15,5];var decArray=[10,20,15,5];function compareFun1(a, b) {

return a - b;}function compareFun2(a, b) {

return b - a;}document.write("mixArray after sorted Alphabetically: ", mixArray.sort(), "<br>");document.write("numArray after sorted Alphabetically: ", numArray.sort(), "<br>");document.write("ascArray after sorted Numerically: ", ascArray.sort(compareFun1), "<br>");document.write("decArray after sorted Numerically: ", decArray.sort(compareFun2), "<br>");document.write("numArray after sorted Numerically: ", numArray.sort(compareFun1), "<br>");</script></body></html>

Page 36: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – sort() sample result

mixArray after sorted Alphabetically: -1,-1.5,1,700,700.5,9,HI,Hi,hinumArray after sorted Alphabetically: -4,-4.25,1,11,2,3,3,7.5,8,9,9.75,900ascArray after sorted Numerically: 5,10,15,20decArray after sorted Numerically: 20,15,10,5numArray after sorted Numerically: -4.25,-4,1,2,3,3,7.5,8,9,9.75,11,900

Page 37: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – slice()

• arrayName.slice(beginIndex[, endIndex])• It returns an extracted segment of an array as a

new array.• It does not modify the original array.• slice() begins at the beginIndex and extracts up

to, but not including, the end index.• If no endIndex is specified, slice() extracts the

element from the beginIndex to the end of the array.

• If the endIndex specified is negative, it indicates the offset from the end of the array.

Page 38: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Array Method – slice() sample<html><head><title>Array slice</title></head><body><h1>Array method – slice()</h1><script language="JavaScript" type="text/javascript">var zList = ["item0", "item1", "item2", "item3", "item4", "item5", "item6", "item7"];var ary_24 = zList.slice(2,4);var ary_2Offset2 = zList.slice(2,-2);var ary_2Toend = zList.slice(2);document.write("New array of slice(2,4): ", ary_24, "<br>");document.write("New array of slice(2,-2): ", ary_2Offset2, "<br>");document.write("New array of slice(2): ", ary_2Toend, "<br>");

document.write("Program end");

</script></body></html>

Page 39: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

A Summary of Array Methods

Method Descriptionconcat(ary2[,ary3,…]) Concatenates two or more arrays and returns the

result as a new array.

join([separator]) Returns all of the elements of an array joined together in a single string delimited by an optional separator, if no separator is specified, a comma is inserted between elements.

pop() Removes and returns the last element of an array.

push(ele1[,ele2,…]) Appends one or more elements on to the end of an array and returns the array’s new length.

reverse() Reverses the order of an array. This method actually modifies the array.

Page 40: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

A Summary of Array Methods (continue…)

Method Descriptionshift() Removes and returns the first element of an array.

slice(beginIndex[, endIndex]) Returns an extracted segment of an array as a new array.

sort([comparefunct]) Sorts the elements of an array. This method actually modifies the array.

splice(startIndex, howMany [,ele1, …]) Modifies the contents of an array by adding and/or removing elements. It returns the items removed. This method is quite powerful.

toString() Returns the array converted to a string; elements are delimited by a comma.

unshift([ele1, ele2,…]) Inserts one or more elements at the front of the array and returns the new length. NOTE: IE 5.5 does not return the new length

Page 41: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Using Numeric Arrays• Creating a Numeric Array (1)

var scores = new Array(4);scores[0] = 39;scores[1] = 40;scores[2] = 100;cores[3] = 49;

• Creating a Numeric Array (2) var scores = new Array(39, 40, 100, 49);

• Creating a Numeric Array (3)var scores = [39, 40, 100, 49];

Page 42: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Understanding Array length

var test = new Array();test[0] = 21;test[5] = 22;test.length // max index = 5, length is 6

Page 43: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Using String Arrays

• Creating a String Array (1)var names = new Array(30);names[0] = "Sue Smith";names[1] = "Paul Baker";

• Creating a String Array (2)var names = new Array("Sue Smith", "Paul Baker");

• Creating a String Array (3)var names = ["Sue Smith", "Paul Baker"];

Page 44: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Splitting a String• JS includes a string method called split, which splits a string into its

component parts. • To use this method, specify the string to split and a character to divide the

parts,var test = "Sue P. Smith";var parts = test.split(" ");

• The split method splits the test string at each space, resulting in three strings.

• These are stored in a string array called parts. • After the split statement, the elements of parts contain the following:

parts[0] = "Sue";parts[1] = "P.";parts[2] = "Smith";

Page 45: CNIT 133 Interactive Web Pags – JavaScript and AJAX Arrays

Joining an Array• JS also includes an array method, join, which

performs the opposite function. • This statement reassembles the parts array into a

string.var fullname = parts.join(" ");

• The value in the parentheses specifies a character to separate the parts of the array.

• In this case, a space is used, resulting in the final string "Sue P. Smith".

• NOTE: if you do not specify a character commas are used.