530 likes | 614 Views
Javascript core objects. 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.
E N D
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.
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.
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
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
Javascript core objects • User-defined objects (introduction last week) • Javascript built-in objects (core objects)
Core objects • Array Object • Boolean Object • Date Object • Function Object • Math Object • Number Object • RegExp Object • String Object
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
Defining an Array Arrays can be created in several different ways • var highScores = new Array(100,200,300,400,500); • var highScores = new Array();highScores[0] = 100;highScores[1] = 200; • var highScores = new Array(5);highScores[0] = 100;highScores[1] = 200;highScores[2] = 300;highScores[3] = 400;highScores[4] = 500;
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
Example <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> <script language="JavaScript"> document.write("<h3>"); document.write("The book array has " + book.length + " elements<br>"); </script>
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
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
Example for Array <body> <script type=”text/javascript”> 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(“; ")); </script> </body>
More example for Array <script type=”text/javascript”> 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(", ")); </script> </body> </html>
More example for Array • Shift/unshift methods • Splice method
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
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
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()
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()
Date objects • Create a Date object var curDate = new Date(); var curDate = new Date (<Date format>); Example of <Date format>: July 4, 2004: 6:25:22 July 4, 2004 2004,7,4
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
Using the Date Object to Display the Date and Time <script type="text/javascript"> // 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";
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("<p>Current date: "+dayNames[dayOfTheWeek]+" "+day+" "+monthNames[month]+" "+year); document.write("<p>Current time: "+hours+":"+minutes+":"+seconds); </script>
More example with Date object • Customizing the Date object with prototype property
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.
Example for Math object <script type="text/javascript"> 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)";
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("<p>"+slogan[subscript].bold()+"</p>"); </script>
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”
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!”); }
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
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.”);
Creating Strings <script type="text/javascript"> customer1 = new String("Eric Kwok"); customer2 = new String("Eric Kwok"); var customer3 = "Jane Yu"; var customer4 = "Jane Yu"; if (customer1==customer2){ document.write("<p>customer1 and customer2 are identical.</p>"); } else{ document.write("<p>customer1 and customer2 are different.</p>"); } if (customer3==customer4){ document.write("<p>customer3 and customer4 are identical.</p>"); } else{ document.write("<p>customer3 and customer4 are different.</p>"); }
Creating Strings (continued) if (customer1.toString()==customer2.toString()) { document.write("<p>customer1.toString() and customer2.toString() are identical.</p>"); } else{ document.write("<p>customer1.toString() and customer2.toString() are different.</p>"); } </script>
Working With Properties String objects have two properties that string literals do not have. • Constructor – customer1.constructor Any public code used to create the object would be displayed. • 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);
Using String Properties <script type="text/javascript"> 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("<p>customer1 and customer2 are identical in length.</p>"); } else { document.write("<p>customer1 and customer2 are different in length.</p>"); } if (customer3.length==customer4.length) { document.write("<p>customer3 and customer4 are identical in length.</p>"); }
Using String Properties (continued) else { document.write("<p>customer3 and customer4 are different in length.</p>"); } if (customer1.toString().length==customer2.toString().length) { document.write("<p>customer1.toString() and customer2.toString() are identical in length.</p>"); } else { document.write("<p>customer1.toString() and customer2.toString() are different in length.</p>"); } </script> </body> </html>
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:
String methods charAt(index) substring(beginPos, endPos) toLowerCase() toUpperCase() indexOf(substr) lastIndexOf(substr)
Using String Methods <script type="text/javascript"> // 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";
Using String Methods (continued) // Converting case customer1=customer1.toLowerCase(); customer2=customer2.toLowerCase(); document.write("<p>Checking customer details for "+customer1+" and "+customer2+".</p>"); // 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."); } } </script> </body> </html>
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
Using Formatting Methods <script type="text/javascript"> 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("<h1>Purchase Summary</h1>"); document.write("<ul>");
Using Formatting Methods(continued) for (i=0; i<5; i++) { if (items[i]<0) { document.write("<li>"+items[i].fontcolor("red")); } else { document.write("<li>"+items[i].fontcolor("blue")); } } document.write("</ul>"); } </script> <form name="purchases"> Item 1: <input type="Text" name="item1"><p> Item 2: <input type="Text" name="item2"><p> Item 3: <input type="Text" name="item3"><p> Item 4: <input type="Text" name="item4"><p> Item 5: <input type="Text" name="item5"><p> <input type="Submit" value="Tabulate Items" onClick="calculate()"> </form>
Adding the Data <script type="text/javascript"> 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("<h1>Credit Card Balance</h1>"); var balance=0.0;
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")); } } </script> <form name="purchases"> Item 1: <input type="Text" name="item1"><p> Item 2: <input type="Text" name="item2"><p> Item 3: <input type="Text" name="item3"><p> Item 4: <input type="Text" name="item4"><p> Item 5: <input type="Text" name="item5"><p> <input type="Submit" value="Calculate" onClick="calculate()"> </form> </body>
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);