Presentation is loading. Please wait.

Presentation is loading. Please wait.

Javascript core objects. Review question Which of the following is TRUE concerning a variable declared globally? a. The variable cannot be accessed anywhere.

Similar presentations


Presentation on theme: "Javascript core objects. Review question Which of the following is TRUE concerning a variable declared globally? a. The variable cannot be accessed anywhere."— Presentation transcript:

1 Javascript core objects

2 Review question Which of the following is TRUE concerning a variable declared globally? a. The variable cannot be accessed anywhere in the script. b. The variable can be accessed only within a function. c. The variable can be accessed only outside of a function. d. The variable can be accessed anywhere within the script.

3 Review question Which of the following is TRUE concerning a variable declared globally? a. The variable cannot be accessed anywhere in the script. b. The variable can be accessed only within a function. c. The variable can be accessed only outside of a function. d. The variable can be accessed anywhere within the script.

4 Review question JavaScript pass variables by which of the following? a. By neither reference nor value b. By value c. By reference d. By value and reference

5 Review question JavaScript pass variables by which of the following? a. By neither reference nor value b. By value c. By reference d. By value and reference

6 Javascript core objects User-defined objects (introduction last week) Javascript built-in objects (core objects)

7 Core objects Array Object Boolean Object Date Object Function Object Math Object Number Object RegExp Object String Object

8 Working With Arrays Arrays are related sets of data Arrays can hold many types of data Numeric String Boolean Objects Arrays Arrays are ordered by an index number Arrays can be sorted

9 Defining an Array Arrays can be created in several different ways 1. var highScores = new Array(100,200,300,400,500); 2. var highScores = new Array(); highScores[0] = 100; highScores[1] = 200; 3. var highScores = new Array(5); highScores[0] = 100; highScores[1] = 200; highScores[2] = 300; highScores[3] = 400; highScores[4] = 500;

10 Array properties Length: return the number of elements in the array Prototype: extends the definition of the array by adding properties and methods Constructor: reference to the object’s constructor

11 Example 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 ");

12 Array Methods concat() – merges two or more arrays into one array join() - converts all items in an array to a string with a delimeter pop() – pops or removes the last element from an array and returns it to the calling statement push() – pushes or adds an new element onto the end of an existing array reverse() – reverses the order of the elements in an existing array shift() – pops the first element of an array returns it to the calling statement

13 Array Methods (continued) unshift() – pushes a new element onto the beginning of an existing array and returns the new length of the array slice() – inserts a range of array elements into a new array splice() – removes or deletes elements from an existing array sort() – rearranges the elements of an array in ascending alphabetical order

14 Example for Array customer = new Array (); customer[0]="Wu Cheng En"; customer[1]="Eric Kwok"; customer[2]="Jane Yu"; customer[3]="Yukio Ashihara"; document.write("Existing customers: "+customer.sort().join(“; "));

15 More example for Array customer = new Array (); customer[0]="Wu Cheng En"; customer[1]="Eric Kwok"; customer[2]="Jane Yu"; customer[3]="Yukio Ashihara"; document.write("Existing customers: "+customer.sort().slice(0,2).join(", "));

16 More example for Array Shift/unshift methods Splice method

17 Review question Which of the following is TRUE when creating a user-defined object? a. A user-defined object cannot have any properties. b. A user-defined object can have only 1 property. c. A user-defined object can have a maximum of three properties. d. A user-defined object can have multiple properties

18 Review question Which of the following is TRUE when creating a user-defined object? a. A user-defined object cannot have any properties. b. A user-defined object can have only 1 property. c. A user-defined object can have a maximum of three properties. d. A user-defined object can have multiple properties

19 Review question Which of the following is the correct syntax to sort an array called Student? a. Student.sort b. Student.sort() c. Student sort d. Student sort()

20 Review question Which of the following is the correct syntax to sort an array called Student? a. Student.sort b. Student.sort() c. Student sort d. Student sort()

21 Date objects Create a Date object var curDate = new Date(); Example of : July 4, 2004: 6:25:22 July 4, 2004 2004,7,4

22 Date Object Methods getDate()Gets the current date getDay()Gets the current day getHours()Gets the current hour getMinutes()Gets the current number of minutes getMonth()Gets the current month getSeconds()Gets the current number of seconds getTime()Gets the current time getTimezoneOffset()Gets the difference (in minutes) from the current timezone and GMT getYear()Gets the current year (two digits) getFullYear()Gets the current year (four digits) parse()Gets the milliseconds elapsed since 1 st January 1970 setDate()Sets the current date setDay()Sets the current day setHours()Sets the current hour setMinutes()Sets the current number of minutes setMonth()Sets the current month setSeconds()Sets the current number of seconds setTime()Sets the current time setYear()Sets the current year (two digits) setFullYear()Sets the current year (four digits) toGMTString()Gets a date in GMT format toLocaleString()Formats a date based on the internationalized locale

23 Using the Date Object Using the methods associated with the Date object require the use of the Date object constructor: var curDate = new Date(); Once you have a Date object, you can get different parts of the current date such as month, day, year, hours, minutes, seconds, etc. You can also use methods to set the different parts of the date Accessing methods or properties are accomplished by using the object.method or object.property syntax

24 Using the Date Object to Display the Date and Time // Current date variables var currentDate=new Date(); var dayOfTheWeek=currentDate.getDay(); var month=currentDate.getMonth(); var day=currentDate.getDate(); var year=currentDate.getYear(); var hours=currentDate.getHours(); var minutes=currentDate.getMinutes(); var seconds=currentDate.getSeconds(); // Day text var dayNames=new Array(7); dayNames[0]="Sun"; dayNames[1]="Mon"; dayNames[2]="Tue";

25 Using the Date Object to Display the Date and Time (continued) dayNames[3]="Wed"; dayNames[4]="Thu"; dayNames[5]="Fri"; dayNames[6]="Sat"; // Month text var monthNames=new Array(12); monthNames[0]="Jan"; monthNames[1]="Feb"; monthNames[2]="Mar"; monthNames[3]="Apr"; monthNames[4]="May"; monthNames[5]="Jun"; monthNames[6]="Jul"; monthNames[7]="Aug"; monthNames[8]="Sep"; monthNames[9]="Oct"; monthNames[10]="Nov"; monthNames[11]="Dec"; // Display date and time document.write(" Current date: "+dayNames[dayOfTheWeek]+" "+day+" "+monthNames[month]+" "+year); document.write(" Current time: "+hours+":"+minutes+":"+seconds);

26 More example with Date object Customizing the Date object with prototype property Customizing the Date object with prototype property

27 Math objects Allows you to work with more advanced arithmetic calculations. Don’t need to create an instance of the Math object with new keyword.

28 Common Math Object Properties ENumeric approximation to Euler’s constant e - approximately 2.71828. LN10Numeric approximation to natural logarithm of 10 – approximately 2.302585. LN2Numeric approximation to natural logarithm of 2 – approximately 0.693147. LOG10ENumeric approximation to logarithm of e base 10 – approximately 0.43429. LOG2ENumeric approximation to logarithm of e base 2 – approximately 1.442695. PI Numeric approximation to , the ratio of a circle’s circumference to its diameter – approximately 3.14159. SQRT2Numeric approximation to the square root of 2, approximately 1.4142. SQRT1_2Numeric approximation to the square root of ½, approximately 0.7071.

29 Common Math Object Methods abs(n)Returns the absolute value of n. acos(n)Returns the arc-cosine of n. asin(n)Returns the arc-sine of n. atan(n)Returns the arc-tangent n. ceil(n)Returns n if n is an integer, or the next integer above n if n is real. cos(n)Returns the cosine of n. exp(n)Returns the value of e to the power of n. floor(n)Returns n if n is an integer, or the next integer below n if n is real. log(n)Returns the value of the natural logarithm of n. max(m, n)Returns m if m>n otherwise returns n. min(m, n)Returns m if m<n otherwise returns n. pow(m, n)Raises m to the power of n. random()Returns a pseudo-randomly generated floating point number between 0 and 1. round(n)Rounds up n to the nearest integer. sin(n)Returns the sine of n. sqrt(n)Returns the square root of n.

30 Example for Math object var slogan=new Array(10); slogan[0]="WizBank - excellence in customer service"; slogan[1]="WizBank - the choice of tomorrow's generation"; slogan[2]="WizBank - future financial services today"; slogan[3]="WizBank - bringing you the best in technology"; slogan[4]="WizBank - customer service with a smile"; slogan[5]="WizBank - 6% home loans (first 25 customers only)";

31 Example for Math objects slogan[6]="WizBank - discount credit card rates until tomorrow"; slogan[7]="WizBank - serving you financially"; slogan[8]="WizBank - #1 in finance for homes"; slogan[9]="WizBank - mortgages are our business"; var subscript=Math.floor(Math.random()*10); document.write(" "+slogan[subscript].bold()+" ");

32 Strings String objects are defined in JavaScript by a pair of single or double quotes. For example: ‘This is a string.’ “This string contains alpha and numeric characters - !@#$%^&*() 1234567890”

33 Strings (continued) String objects have many methods by which they can be manipulated. Strings are often used to build and update live pages in HTML. Properties of strings can be used to validate data, for example, using the length property of a string can determine if too many characters have been entered into a text field. if(document.entryform.phoneNumber.value.length > 7){ window.alert(“Invalid Phone Number!”); }

34 String Objects A string object encapsulates the data, methods and properties of strings. Data – an ordered set of characters Method – converting case of string, extracting portions of a string, etc. Property – length of a string in characters

35 Creating Strings Strings can be created implicitly or explicitly Implicitly: (string literal) var myString = “This is an implicit string.”; Explicitly: (string object) var myString = new String(“This is an explicit string.”);

36 Creating Strings customer1 = new String("Eric Kwok"); customer2 = new String("Eric Kwok"); var customer3 = "Jane Yu"; var customer4 = "Jane Yu"; if (customer1==customer2){ document.write(" customer1 and customer2 are identical. "); } else{ document.write(" customer1 and customer2 are different. "); } if (customer3==customer4){ document.write(" customer3 and customer4 are identical. "); } else{ document.write(" customer3 and customer4 are different. "); }

37 Creating Strings (continued) if (customer1.toString()==customer2.toString()) { document.write(" customer1.toString() and customer2.toString() are identical. "); } else{ document.write(" customer1.toString() and customer2.toString() are different. "); }

38 Working With Properties String objects have two properties that string literals do not have. 1. Constructor – customer1.constructor Any public code used to create the object would be displayed. 2. Prototype – myString.prototype.dateCreated = “01/01/2004” Window.alert(myString.dateCreated) The length property is common to string literals and string objects. var stringLiteral = “This is a string literal.”; window.alert(stringLiteral.length);

39 Using String Properties customer1 = new String("Eric Kwok"); customer2 = new String("Eric Kwok"); var customer3 = "Jane Yu"; var customer4 = "Jane Yu"; if (customer1.length==customer2.length) { document.write(" customer1 and customer2 are identical in length. "); } else { document.write(" customer1 and customer2 are different in length. "); } if (customer3.length==customer4.length) { document.write(" customer3 and customer4 are identical in length. "); }

40 Using String Properties (continued) else { document.write(" customer3 and customer4 are different in length. "); } if (customer1.toString().length==customer2.toString().length) { document.write(" customer1.toString() and customer2.toString() are identical in length. "); } else { document.write(" customer1.toString() and customer2.toString() are different in length. "); }

41 Manipulating Strings Strings can be manipulated in a number of ways including: changing the case breaking apart a string into smaller parts extracting sub-strings This manipulation is possible because JavaScript treats a string as an array. For example, var jsString = “A JavaScript string” has the following subscript values: AJavaScriptstring 01234567891010 111212 1313 1414 1515 1616 1717 1818

42 String methods charAt(index) substring(beginPos, endPos) toLowerCase() toUpperCase() indexOf(substr) lastIndexOf(substr)

43 Using String Methods // New customer entries var customer1 = "ERIC KWOK"; var customer2 = "JANE YU"; // Delinquent customer entries var delinquents=new Array(4); delinquents[0]="John Smith"; delinquents[1]="Eric Kwok"; delinquents[2]="Jane Doe"; delinquents[3]="John Lee";

44 Using String Methods (continued) // Converting case customer1=customer1.toLowerCase(); customer2=customer2.toLowerCase(); document.write(" Checking customer details for "+customer1+" and "+customer2+". "); // Checking delinquents for (i=0; i<4; i++) { if (customer1==delinquents[i].toLowerCase()) { document.write(customer1+" is on the delinquent cardholder's list."); } for (i=0; i<4; i++) { if (customer2==delinquents[i].toLowerCase()) { document.write(customer2+" is on the delinquent cardholder's list."); }

45 Formatting Strings The formatting of strings is accomplished by using string methods such as: big() – increases the size of the text blink() – causes the text to blink bold() – bolds the string fontcolor() – changes the font color of the text fontsize() – changes the size of a font italics() – italicizes the text small() – decreases the size of the text strike() – strikes through the text sub() – subscripts the text sup() – superscripts the text

46 Using Formatting Methods function calculate() { var items=new Array(5); items[0]=document.purchases.item1.value; items[1]=document.purchases.item2.value; items[2]=document.purchases.item3.value; items[3]=document.purchases.item4.value; items[4]=document.purchases.item5.value; document.write(" Purchase Summary "); document.write(" ");

47 Using Formatting Methods (continued) for (i=0; i<5; i++) { if (items[i]<0) { document.write(" "+items[i].fontcolor("red")); } else { document.write(" "+items[i].fontcolor("blue")); } document.write(" "); } Item 1: Item 2: Item 3: Item 4: Item 5:

48 Adding the Data function calculate() { var items=new Array(5); items[0]=document.purchases.item1.value; items[1]=document.purchases.item2.value; items[2]=document.purchases.item3.value; items[3]=document.purchases.item4.value; items[4]=document.purchases.item5.value; //document.write(" Credit Card Balance "); var balance=0.0;

49 Adding the Data (continued) for (i=0; i<5; i++) { balance=balance+parseFloat(items[i]); } if (balance<0.0) { document.write("Dear customer, your balance is $"+balance.toString().fontcolor("red")); } else { document.write("Dear customer, your balance is $"+balance.toString().fontcolor("blue")); } Item 1: Item 2: Item 3: Item 4: Item 5:

50 Extracting Strings Extracting substrings from longer strings is commonly used to extract specific length substrings. This technique can be used to separate the individual components of a database record. var customer1 = "Watters......................Paul......555- 1234"; var customerLname = customer1.substring(0,29); var customerFname = customer1.substring(29,39); var customerPhone = customer1.substring(39,47);

51 Lab Step 1: Practice Javascript // Insert your code here

52 Lab Step 2: In your script, do the followings: - Create a String object containing “Jose lived in San Jose for many years” - Find and display Index of the second “Jose” - Get the substring ear from years and display it - Display the string in a blue, italic font, point size 12, all upper case


Download ppt "Javascript core objects. Review question Which of the following is TRUE concerning a variable declared globally? a. The variable cannot be accessed anywhere."

Similar presentations


Ads by Google