Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— 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 The Array Object An Array of Books 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"; document.write(" "); for(var i in book){ document.write("book[" + i + "] "+ book[i] + " "); }

5 Populating an Array with a for Loop (Example 2) The Array Object An Array of Numbers var years = new Array(10); for(var i=0; i < years.length; i++ ){ years[i]=i + 2000; document.write("years[" + i + "] = "+ years[i] + " "); }

6 Creating and Populating an Array Simultaneously (Example 3) The Array Object An Array of Colored Strings var colors = new Array("red", "green", "blue", "purple", "yellow"); for(var i in colors){ document.write(" "); document.write("colors[" + i + "] = "+ colors[i] + " "); } document.write(document.bgColor=colors[i]);

7 Associative Arrays (Example 4) Associative Arrays An Array Indexed by Strings var states = new Array(); states["CA"] = "California"; states["ME"] = "Maine"; states["MT"] = "Montana"; for( var i in states ){ document.write("The index is: " + i ". ”); document.write(“The value is: " + states[i] + ". "); }

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 Array Properties 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"; document.write(" "); document.write("The book array has " + book.length + " elements ");

10 Array Methods – concat() (example6) Array concat() methods var names1=new Array("Dan", "Liz", "Jody" ); var names2=new Array("Tom", "Suzanne"); document.write(" First array: "+ names1 + " "); document.write(" Second array: "+ names2 + " "); document.write(" After the concatenation "); names1 = names1.concat(names2); document.write(names1);

11 Array Methods – pop() (example7) Some Array Methods var names=new Array("Tom", "Dan", "Liz", "Jody"); document.write(" Original array: "+ names +" "); var newstring=names.pop(); // Pop off last element of array document.write("Element popped: "+ newstring); document.write(" New array: "+ names + " ");

12 Array Methods – push() (example8) Array push() method var names=new Array("Tom","Dan", "Liz", "Jody"); document.write(" Original array: "+ names + " "); names.push("Daniel","Christian"); document.write("New array: "+ names + " ");

13 Array Methods – shift() and unshift() (example9) Array shift() and unshift() methods var names=new Array("Dan", "Liz", "Jody" ); document.write(" Original array: "+ names + " "); 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(" New array after the unshift: " + names);

14 Array Methods – slice() (example10) Array slice() method var names=new Array("Dan", "Liz", "Jody", "Christian", "William"); document.write(" Original array: "+ names + " "); var sliceArray=names.slice(2, 4); document.write("New array after the slice: "); document.write(sliceArray);

15 Array Methods – splice() (example11) Array splice() method // splice(starting_pos, number_to_delete, new_values ) var names=new Array("Tom","Dan", "Liz", "Jody"); document.write(" Original array: "+ names + " "); names.splice(1, 2, "Peter","Paul","Mary"); document.write("New array: "+ names + " ");

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) Time and Date Date and Time var now = new Date(); // now is an instance of a Date object document.write(" "); document.write(" Local time: " + now + " "); var hours=now.getHours(); var minutes=now.getMinutes(); var seconds=now.getSeconds(); var year=now.getFullYear(); document.write("The full year is " + year +" "); document.write(" The time is: " + hours + ":" + minutes + ":" + seconds); document.write(" ");

19 Manipulating Date and Time - Example 14 Countdown 'till Christmas 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 " + days + " shopping days left \'til Christmas! "; document.write(str+" ");

20 Customizing the Date Object with the prototype property (example 15) The Prototype Property // 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; var today=new Date(); document.write("Today is " + today.DayOfWeek() + ". ");

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 The Math Object Math object Methods--sqrt(),pow() Math object Property--PI var num=16; document.write(" The square root of " +num+ " is "); document.write(Math.sqrt(num),". "); document.write("PI is "); document.write(Math.PI); document.write(". "+num+" raised to the 3rd power is " ); document.write(Math.pow(num,3)); document.write(". ");

23 Math Object – ceil(number), floor(number), round(number) The Math Object Rounding Numbers var num=16.3; document.write(" The number being manipulated is: ", num, " "); document.write("The Math.floor method rounds down: " + Math.floor(num) + " "); document.write("The Math.ceil method rounds up: " + Math.ceil(num) +" "); document.write("The Math.round method rounds to the nearest integer: " + Math.round(num) + " ");

24 Math Object – random() Random Numbers var n = 10; for(i=0; i < 10;i++){ // Generate random numbers between 0 and 10 document.write(Math.floor(Math.random()* (n + 1)) + " "); }

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 The String Object Primitive and String Objects 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 "+ typeof(first_string)); document.write(". The second string is of type "+ typeof(next_string) +". ");

27 String Object – length property The String Object Length of Strings 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(" \""+ next_string+"\" contains "+ next_string.length+" characters. "); document.write("...not to imply that war is equal to peace... ");

28 String Object – prototype property The Prototype Property // Customize String Functions function ucLarge(){ var str=this.bold().fontcolor("white").toUpperCase().fontsize("22"); return( str); } String.prototype.ucL=ucLarge; var string="Watch Your Step!!"; document.write(string.ucL()+" ");

29 String Object – fontcolor(color), fontsize(size), bold(), big(), italics() String object Working with String Objects: var str1 = new String("Hello world!"); // Use a String constructor var str2 = "It's a beautiful day today."; document.write(str1 + " “); document.write(str1.fontcolor("blue")+" "); document.write(str1.fontsize(8).fontcolor("red").bold()+" "); document.write(str1.big()+ " "); document.write("Good-bye, ".italics().bold().big() + str2 + " ");

30 String Object – indexOf() Substrings Searching for an @ sign 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(" OK. ");

31 String Object – lastIndexOf(substr,startpos), substr(startpos,size), toUpperCase() More String Manipulation Working with String Manipulation Methods function break_tag(){ document.write(" "); } document.write(" "); var str1 = new String("The merry, merry month of June..."); document.write("In the string: "+ str1 ); document.write(" 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(" str1.substr(4,5) returns " + str1.substr(4,5)); break_tag(); document.write(str1.toUpperCase()); document.write(" ");

32 String Object – split(delimiter), charAt(index) Extracting Substrings Extracting substrings var straddr = "DanielSavage@dadserver.org"; document.write(" His name is " + straddr.substr(0,6) + ". "); var namesarr = straddr.split("@" ); document.write( "The user name is " + namesarr[0] + ". "); document.write( "and the mail server is " + namesarr[1] + ". "); document.write( "The first character in the string is " + straddr.charAt(0)+ ". "); document.write( "and the last character in the string is “ + straddr.charAt(straddr.length - 1) + ". ");

33 String Object – replace(search value, replace value), search(regexp) (example26) Search and Replace Search and Replace Methods var straddr = "DanielSavage@dadserver.org"; document.write( "The original string is "+ straddr + " "); document.write( "The new string is “ + straddr.replace("Daniel","Jake") + " "); var index=straddr.search("dad"); document.write("The search() method found \"dad\" at position "+ index +" "); var mysubstr=straddr.substr(index,3); document.write("After replacing \"dad\" with \"POP\" "); document.write(straddr.replace(mysubstr,"POP")+" ");

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) Number Contants Constants 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(" The largest number is " + largest+ " "); document.write("The smallest number is "+ smallest + " "); document.write("The number as a string (base 2): "+ num1.toString(2)); document.write(" The number as a string (base 8): "+ num2.toString(8)); document.write("The square root of -25 is: "+ Math.sqrt(-25) + " ");

36 Number Object – toFixed() (example 28) Number Object Formatting Numbers var n = new Number(22.425456); document.write(" The unformatted number is " + n + " "); document.write("The formatted number is "+ n.toFixed(2) + " "); document.write("The formatted number is "+ n.toFixed(3) + " ");

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 Boolean Object The Boolean Object 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 +" "); document.write("The value 1 is boolean "+ bool2 +" "); document.write("The value of the empty string is boolean "+ bool3+ " "); document.write("The value of null is boolean "+ bool4+ " "); document.write( "The value of NaN is boolean "+ bool5 +" ");

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

40 Function Object – example 30 Function Object Anonymous Functions and the Function Constructor var sum = new Function("a","b", "return a + b; "); window.onload = new Function ( "document.bgColor='yellow';"); document.write( "The sum is " + sum(5,10)+ " "); document.write( "The background color is yellow ");

41 With keyword – example 31 The with Keyword Using the with keyword var yourname=prompt("What is your name? ",""); // Create a string object with(yourname){ document.write("Welcome " + yourname + " to our planet!! "); document.write("Your name is " + length + " characters in length. "); document.write("Your name in uppercase: " + toUpperCase() + ". "); document.write("Your name in lowercase: " + toLowerCase() + ". "); }


Download ppt "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."

Similar presentations


Ads by Google