1 / 45

CNIT 133 Interactive Web Pags – JavaScript and AJAX

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.

blemus
Download Presentation

CNIT 133 Interactive Web Pags – JavaScript and AJAX

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CNIT 133 Interactive Web Pags –JavaScript and AJAX Arrays

  2. 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.

  3. 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

  4. Arrays (continue…) • There are three ways to declare an array. • With new operator var 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 time var 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) varweekendDays = ["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.

  5. 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 array var 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

  6. 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.

  7. 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.

  8. 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()).

  9. 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 defined a = new Array(10); //a.length == 10, empty elements 0-9 defined a = new Array(1,2,3); //a.length == 3, elements 0-2 defined a = [4,5]; //a.length == 2, element 0 & 1 defined a[5] = -1; //a.length == 6, elements 0,1 and 5 defined a[49] = 0; //a.length == 50, elements 0,1,5, and 49 defined

  10. 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]); } }

  11. 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>

  12. 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.

  13. 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>

  14. 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>

  15. Empty elements at the end of an array literal result • Result of Netscape 0. Lemonade 1. Ice tea 2. Pepsi 3. undefined 4. undefined • Result of IE and Opera 0. Lemonade 1. Ice tea 2. Pepsi 3. undefined 4. undefined 5. undefined

  16. 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.

  17. 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.

  18. 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>

  19. 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>");

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

  21. 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>

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

  23. 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 * 7 var product = table[5][7]; // 35

  24. 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()

  25. 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.

  26. 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>

  27. 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 data partyInvites = oldFriends + newFriends; // partyInvites is a string with strings from oldFriends + newFriends, cannot use for/loop to get the data

  28. 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>

  29. 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.

  30. 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>

  31. 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.

  32. 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>

  33. 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();

  34. 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; }

  35. 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>

  36. 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

  37. 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.

  38. 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>

  39. A Summary of Array Methods

  40. A Summary of Array Methods (continue…)

  41. 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];

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

  43. 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"];

  44. 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";

  45. 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.

More Related