1 / 41

Unit 7

Unit 7. JavaScript Core Objects. Core Objects. Core Objects are objects built right into the language. For a complete list of properties and objects available in JavaScript, look at your CD at D:JavaScript 1.5 Core Guide and D:JavaScript 1.5 Core Reference.

lee-cline
Télécharger la présentation

Unit 7

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. Unit 7 JavaScript Core Objects

  2. Core Objects • Core Objects are objects built right into the language. • For a complete list of properties and objects available in JavaScript, look at your CD at D:\JavaScript 1.5 Core Guide and D:\JavaScript 1.5 Core Reference. • Today we will cover the Array Object, the Date Object, the Math Object, the Wrapper (string, number, boolean, function) Objects.

  3. Array Objects • An array is a collection of elements. Each element is accessed with an index value enclosed in square brackets. • Arrays must be declared before they can be used. • The new keyword is used to dynamically create the Array object. The size can be passed as argument, but it is not necessary. JavaScript allocates memory as needed. Values can be assigned when it is constructed, but this is also not necessary. • Elements can be of any type. • You can create as many instances as you like of the Array object.

  4. Example <html> <head><title>The Array Object</title> <h2>An Array of Books</h2> <script language="JavaScript"> var book = new Array(6); // Create an Array object book[0] = "War and Peace"; // Assign values its elements book[1] = "Huckleberry Finn"; book[2] = "The Return of the Native"; book[3] = "A Christmas Carol"; book[4] = "The Yearling"; book[5] = "Exodus"; </script> </head> <body bgcolor="lightblue"> <script language="JavaScript"> document.write("<h3>"); for(var i in book){ document.write("book[" + i + "] "+ book[i] + "<br>"); } </script> </body> </html>

  5. Populating an Array with a for Loop (Example 2) <html> <head><title>The Array Object</title> <body> <h2>An Array of Numbers</h2> <script language="JavaScript"> var years = new Array(10); for(var i=0; i < years.length; i++ ){ years[i]=i + 2000; document.write("years[" + i + "] = "+ years[i] + "<br>"); } </script> </body> </html>

  6. Creating and Populating an Array Simultaneously (Example 3) <html> <head><title>The Array Object</title></head> <body> <h2>An Array of Colored Strings</h2> <script language="JavaScript"> var colors = new Array("red", "green", "blue", "purple", "yellow"); for(var i in colors){ document.write("<font color='"+colors[i]+"'>"); document.write("colors[" + i + "] = "+ colors[i] + "<br>"); } document.write(document.bgColor=colors[i]); </script> </body> </html>

  7. Associative Arrays (Example 4) <html> <head><title>Associative Arrays</title></head> <body> <h2>An Array Indexed by Strings</h2> <script language="JavaScript"> var states = new Array(); states["CA"] = "California"; states["ME"] = "Maine"; states["MT"] = "Montana"; for( var i in states ){ document.write("The index is:<em> " + i ".</em>”); document.write(“The value is: <em>" + states[i] + ".</em><br>"); } </script> </body> </html>

  8. Array Properties and Methods • As an object, an Array has properties to describe it and methods to manipulate it. • Properties: • constructor -> references the object’s constructor • length -> returns the number of elements in the array • prototype -> extends the definition of the array by adding properties and methods.

  9. Example 5 – length property <html> <head> <title>Array Properties</title> <h2>Array Properties</h2> <script language="JavaScript"> var book = new Array(6); // Create an Array object book[0] = "War and Peace"; // Assign values to elements book[1] = "Huckleberry Finn"; book[2] = "The Return of the Native"; book[3] = "A Christmas Carol"; book[4] = "The Yearling"; book[5] = "Exodus"; </script> </head> <body bgcolor="lightblue"> <script language="JavaScript"> document.write("<h3>"); document.write("The book array has " + book.length + " elements<br>"); </script> </body> </html>

  10. Array Methods – concat() (example6) <html> <head><title>Array concat() methods</title></head> <body> <script language="JavaScript"> var names1=new Array("Dan", "Liz", "Jody" ); var names2=new Array("Tom", "Suzanne"); document.write("<b>First array: "+ names1 + "<br>"); document.write("<b>Second array: "+ names2 + "<br>"); document.write("<b>After the concatenation <br>"); names1 = names1.concat(names2); document.write(names1); </script> </body> </html>

  11. Array Methods – pop() (example7) <html> <head><title>Some Array Methods</title></head> <body> <script language="JavaScript"> var names=new Array("Tom", "Dan", "Liz", "Jody"); document.write("<b>Original array: "+ names +"<br>"); var newstring=names.pop(); // Pop off last element of array document.write("Element popped: "+ newstring); document.write("<br>New array: "+ names + "</b>"); </script> </body> </html>

  12. Array Methods – push() (example8) <html> <head><title>Array push() method</title></head> <body> <script language="JavaScript"> var names=new Array("Tom","Dan", "Liz", "Jody"); document.write("<b>Original array: "+ names + "<br>"); names.push("Daniel","Christian"); document.write("New array: "+ names + "</b>"); </script> </body> </html>

  13. Array Methods – shift() and unshift() (example9) <html> <head><title>Array shift() and unshift() methods</title></head> <body> <script language="JavaScript"> var names=new Array("Dan", "Liz", "Jody" ); document.write("<b>Original array: "+ names + "<br>"); names.shift(); document.write("New array after the shift: " + names); names.unshift("Nicky","Lucy"); // Add new elements to the beginning of the array document.write("<br>New array after the unshift: " + names); </script> </body> </html>

  14. Array Methods – slice() (example10) <html> <head><title>Array slice() method</title></head> <body> <script language="JavaScript"> var names=new Array("Dan", "Liz", "Jody", "Christian", "William"); document.write("<b>Original array: "+ names + "<br>"); var sliceArray=names.slice(2, 4); document.write("New array after the slice: "); document.write(sliceArray); </script> </body> </html>

  15. Array Methods – splice() (example11) <html> <head><title>Array splice() method</title></head> <body> <script language="JavaScript"> // splice(starting_pos, number_to_delete, new_values ) var names=new Array("Tom","Dan", "Liz", "Jody"); document.write("<b>Original array: "+ names + "<br>"); names.splice(1, 2, "Peter","Paul","Mary"); document.write("New array: "+ names + "</b>"); </script> </body> </html>

  16. Date Object • The Date object manipulates date and time. • You can create as many instances as you like. • Date is based on the Unix date starting at Jan1, 1970 (GMT), and does not support dates before that time. Time is measured in milliseconds. • Date object returns times and dates that are local to the browser, not the server. • If no arguments are passed to the Date object constructor, it returns the local date and time.

  17. Formats of Date object constructor • var Date = new Date() • var Date = new Date(“July 4, 2004, 6:25:22”); • var Date = new Date(“July 4, 2004”); • var Date = new Date(2004, 7, 4, 6, 25, 22); • var Date = new Date(2004, 7, 4); • var Date = new Date(Milliseconds);

  18. Date Methods (example 13) <html> <head><title>Time and Date</title></head> <body bgcolor="lightblue"><h2>Date and Time</h2> <script language="JavaScript"> var now = new Date(); // now is an instance of a Date object document.write("<font size='+1'>"); document.write("<b>Local time:</b> " + now + "<br>"); var hours=now.getHours(); var minutes=now.getMinutes(); var seconds=now.getSeconds(); var year=now.getFullYear(); document.write("The full year is " + year +"<br>"); document.write("<b>The time is:</b> " + hours + ":" + minutes + ":" + seconds); document.write("</font>"); </script> </body> </html>

  19. Manipulating Date and Time - Example 14 <html> <head><title>Countdown 'till Christmas</title></head> <body bgColor="#00FF99"> <font face="ariel" size=5 color=red> <script language="JavaScript"> var today = new Date(); var fullyear = today.getFullYear(); var future = new Date("December 25, "+ fullyear); var diff = future.getTime() - today.getTime(); // number of milliseconds var days = Math.floor(diff / (1000 * 60 * 60 * 24 )); // convert to days var str="Only <u>" + days + "</u> shopping days left \'til Christmas! "; document.write(str+"<br>"); </script> </body> </html>

  20. Customizing the Date Object with the prototype property (example 15) <html> <head><title>The Prototype Property</title> <script language = "javascript"> // Customize the Date function weekDay(){ var now = this.getDay(); var names = new Array(7); names[0]="Sunday"; names[1]="Monday"; names[2]="Tuesday"; names[3]="Wednesday"; names[4]="Thursday"; names[5]="Friday"; names[6]="Saturday"; return(names[now]); } Date.prototype.DayOfWeek=weekDay; </script> </head> <body bgcolor="pink"> <font face="arial" size="+1"> <center> <script language="JavaScript"> var today=new Date(); document.write("Today is " + today.DayOfWeek() + ".<br>"); </script> </body> </html>

  21. Math Object • Always starts with the uppercase M. • You do not need to create an instance of the Math object with the “new” keyword. • There are innumerous properties and methods for this built-in object.

  22. Math Object – sqrt(number), pow(x,y) and Pi <html> <head><title>The Math Object</title></head> <body> <h2>Math object Methods--sqrt(),pow()<br> Math object Property--PI</h2> <P> <script language="JavaScript"> var num=16; document.write("<h3>The square root of " +num+ " is "); document.write(Math.sqrt(num),".<br>"); document.write("PI is "); document.write(Math.PI); document.write(".<br>"+num+" raised to the 3rd power is " ); document.write(Math.pow(num,3)); document.write(".</h3></font>"); </script> </body> </html>

  23. Math Object – ceil(number), floor(number), round(number) <html> <head><title>The Math Object</title></head> <body> <h2>Rounding Numbers</h2> <p> <h3> <script language="JavaScript"> var num=16.3; document.write("<I>The number being manipulated is: ", num, "</I><br><br>"); document.write("The <I>Math.floor</I> method rounds down: " + Math.floor(num) + "<br>"); document.write("The <I>Math.ceil</I> method rounds up: " + Math.ceil(num) +"<br>"); document.write("The <I>Math.round</I> method rounds to the nearest integer: " + Math.round(num) + "<br>"); </script> </h3> </body> </html>

  24. Math Object – random() <html> <head><title>Random Numbers</title> <font size="+1"> <script language="JavaScript"> var n = 10; for(i=0; i < 10;i++){ // Generate random numbers between 0 and 10 document.write(Math.floor(Math.random()* (n + 1)) + "<br>"); } </script> </head> <body></body> </html>

  25. Wrapper Object • For each of the primitive data types there is an object (String object, Number object, Boolean object). • They provide properties and methods that can be defined for the object.

  26. String Object <html> <head><title>The String Object</title></head> <body bgcolor=pink><font face="arial" size=+1> <h2>Primitive and String Objects</h2> <script language="JavaScript"> var first_string = "The winds of war are blowing."; var next_string = new String("There is peace in the valley."); document.write("The first string is of type<em> "+ typeof(first_string)); document.write(".</em><br>The second string is of type<em> "+ typeof(next_string) +".<br>"); </script> </body> </html>

  27. String Object – length property <html> <head><title>The String Object</title></head> <body bgColor="lightblue"> <font face="arial" size=+1> <h3>Length of Strings</h3> <script language="JavaScript"> var first_string = "The winds of war are blowing."; var next_string = new String("There is peace in the valley."); document.write("\""+first_string +"\" contains "+ first_string.length + " characters."); document.write("<br>\""+ next_string+"\" contains "+ next_string.length+" characters.<br>"); document.write("<font size=-1><em>...not to imply that war is equal to peace...<br>"); </script> </body> </html>

  28. String Object – prototype property <html> <head><title>The Prototype Property</title> <script language = "javascript"> // Customize String Functions function ucLarge(){ var str=this.bold().fontcolor("white").toUpperCase().fontsize("22"); return( str); } String.prototype.ucL=ucLarge; </script> </head> <body bgcolor=black><center> <script language="JavaScript"> var string="Watch Your Step!!"; document.write(string.ucL()+"<br>"); </script> <img src="high_voltage.gif"> </body> </html>

  29. String Object – fontcolor(color), fontsize(size), bold(), big(), italics() <html> <head><title>String object</title></head> <body bgcolor="yellow"> <font size="+1" face="arial"> <h2>Working with String Objects:</h2> <script language="JavaScript"> var str1 = new String("Hello world!"); // Use a String constructor var str2 = "It's a beautiful day today."; document.write(str1 + "<br>“); document.write(str1.fontcolor("blue")+"<br>"); document.write(str1.fontsize(8).fontcolor("red").bold()+"<br>"); document.write(str1.big()+ "<br>"); document.write("Good-bye, ".italics().bold().big() + str2 + "<br>"); </script> </body> </html>

  30. String Object – indexOf() <html> <head><title>Substrings</title></head> <body bgcolor=lightgreen> <font face="arial" size="+1"> Searching for an @ sign <script language="JavaScript"> var email_addr = prompt("What is your email address? ",""); while(email_addr.indexOf("@") == -1 ){ alert( "Invalid email address."); email_addr = prompt("What is your email address? ",""); } document.write("<br>OK.<br>"); </script> </body> </html>

  31. String Object – lastIndexOf(substr,startpos), substr(startpos,size), toUpperCase() <html> <head><title>More String Manipulation</title></head> <body> <h2>Working with String Manipulation Methods</h2> <script language="JavaScript"> function break_tag(){ document.write("<br>"); } document.write("<h3>"); var str1 = new String("The merry, merry month of June..."); document.write("In the string:<em> "+ str1 ); document.write("</em> the first 'm' is at position " + str1.indexOf("m")); break_tag(); document.write("The last 'm' is at position " + str1.lastIndexOf("m")); break_tag(); document.write("<em>str1.substr(4,5)</em> returns<em> " + str1.substr(4,5)); break_tag(); document.write(str1.toUpperCase()); document.write("</h3>"); </script> </body> </html>

  32. String Object – split(delimiter), charAt(index) <html> <head><title>Extracting Substrings</title></head> <body bgcolor=lightgreen> <font face="arial" size="+1">Extracting substrings<font size="-1"> <script language="JavaScript"> var straddr = "DanielSavage@dadserver.org"; document.write("<br>His name is<em> " + straddr.substr(0,6) + "</em>.<br>"); var namesarr = straddr.split("@" ); document.write( "The user name is<em> " + namesarr[0] + "</em>.<br>"); document.write( "and the mail server is<em> " + namesarr[1] + "</em>.<br>"); document.write( "The first character in the string is <em>" + straddr.charAt(0)+ "</em>.<br>"); document.write( "and the last character in the string is <em>“ + straddr.charAt(straddr.length - 1) + "</em>.<br>"); </script> </body> </html>

  33. String Object – replace(search value, replace value), search(regexp) (example26) <html> <head><title>Search and Replace</title></head> <body bgcolor=lightgreen> <font face="arial" size="+1">Search and Replace Methods<br><font size="-1"> <script language="JavaScript"> var straddr = "DanielSavage@dadserver.org"; document.write( "The original string is "+ straddr + "<br>"); document.write( "The new string is “ + straddr.replace("Daniel","Jake") + "<br>"); var index=straddr.search("dad"); document.write("The search() method found \"dad\" at position "+ index +"<br>"); var mysubstr=straddr.substr(index,3); document.write("After replacing \"dad\" with \"POP\" <br>"); document.write(straddr.replace(mysubstr,"POP")+"<br>"); </script> </body> </html>

  34. Number Object • The Number Object gives you properties and methods to handle and customize numeric data. It is a wrapper for the primitive numeric values. • The Number() constructor takes a numeric value as its argument.

  35. Number Object – MAX_VALUE, MIN_VALUE, toString(radix) (example27) <html> <head><title>Number Contants</title></head> <body bgcolor=orange><font color="black" size="+1"> <h2>Constants</h2> <script language="JavaScript"> var largest = Number.MAX_VALUE; var smallest = Number.MIN_VALUE; var num1 = 20; // A primitive numeric value var num2 = new Number(13); // Creating a Number object document.write("<b>The largest number is " + largest+ "<br>"); document.write("The smallest number is "+ smallest + "<br>"); document.write("The number as a string (base 2): "+ num1.toString(2)); document.write("<br>The number as a string (base 8): "+ num2.toString(8)); document.write("The square root of -25 is: "+ Math.sqrt(-25) + "<br>"); </script> </body> </html>

  36. Number Object – toFixed() (example 28) <html> <head><title>Number Object</title></head> <body bgcolor=orange><font color="black" size="+1"> <h2>Formatting Numbers</h2> <script language="JavaScript"> var n = new Number(22.425456); document.write("<b>The unformatted number is " + n + "<br>"); document.write("The formatted number is "+ n.toFixed(2) + "<br>"); document.write("The formatted number is "+ n.toFixed(3) + "<br>"); </script> </body> </html>

  37. Boolean Object • It is used to convert a non-Boolean value to a Boolean value, either true or false. • There is one property: prototype • There is one method: toString()

  38. Boolean Object – Example 29 <html> <head><title>Boolean Object</title></head> <body bgcolor=aqua> <font face="arial" size="+1"><b>The Boolean Object<br><font size="-1"> <script language="JavaScript"> var bool1= new Boolean( 0); var bool2 = new Boolean(1); var bool3 = new Boolean(""); var bool4 = new Boolean(null); var bool5 = new Boolean(NaN); document.write("The value 0 is boolean "+ bool1 +"<br>"); document.write("The value 1 is boolean "+ bool2 +"<br>"); document.write("The value of the empty string is boolean "+ bool3+ "<br>"); document.write("The value of null is boolean "+ bool4+ "<br>"); document.write( "The value of NaN is boolean "+ bool5 +"<br>"); </script> </body> </html>

  39. Function Object • Properties: length, prototype • Methods: apply(), call()

  40. Function Object – example 30 <html> <head><title>Function Object</title></head> <body bgcolor=lightgreen> <font face="arial" size="+1"> <center>Anonymous Functions and the Function Constructor <p> <script language="JavaScript"> var sum = new Function("a","b", "return a + b; "); window.onload = new Function ( "document.bgColor='yellow';"); document.write( "The sum is " + sum(5,10)+ "<br>"); document.write( "The background color is yellow<br>"); </script> </body> </html>

  41. With keyword – example 31 <html> <head><title>The with Keyword</title></head> <body> <h2>Using the <em>with</em> keyword</h2> <p> <h3> <script language="JavaScript"> var yourname=prompt("What is your name? ",""); // Create a string object with(yourname){ document.write("Welcome " + yourname + " to our planet!!<br>"); document.write("Your name is " + length + " characters in length.<br>"); document.write("Your name in uppercase: " + toUpperCase() + ".<br>"); document.write("Your name in lowercase: " + toLowerCase() + ".<br>"); } </script> </h3> </body> </html>

More Related