Javascript core objects

Preview:

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

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.

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

NumericStringBooleanObjectsArrays

Arrays are ordered by an index number Arrays can be sorted

Defining an Array

Arrays can be created in several different ways1. 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;

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 objectbook[0] = "War and Peace"; // Assign values to elementsbook[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 arrayjoin() - converts all items in an array to a string with

a delimeterpop() – pops or removes the last element from an

array and returns it to the calling statementpush() – pushes or adds an new element onto the

end of an existing arrayreverse() – reverses the order of the elements in an

existing arrayshift() – 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

Date Object MethodsgetDate() Gets the current date

getDay() Gets the current daygetHours() Gets the current hourgetMinutes() Gets the current number of minutesgetMonth() Gets the current monthgetSeconds() Gets the current number of secondsgetTime() Gets the current timegetTimezoneOffset() Gets the difference (in minutes) from the current

timezone and GMTgetYear() Gets the current year (two digits)getFullYear() Gets the current year (four digits)parse() Gets the milliseconds elapsed since 1st January 1970setDate() Sets the current datesetDay() Sets the current daysetHours() Sets the current hoursetMinutes() Sets the current number of minutessetMonth() Sets the current monthsetSeconds() Sets the current number of secondssetTime() Sets the current timesetYear() Sets the current year (two digits)setFullYear() Sets the current year (four digits)toGMTString() Gets a date in GMT formattoLocaleString() Formats a date based on the internationalized locale

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.

Common Math Object Properties

E Numeric approximation to Euler’s constant e - approximately 2.71828.

LN10 Numeric approximation to natural logarithm of 10 – approximately 2.302585.

LN2 Numeric approximation to natural logarithm of 2 – approximately 0.693147.

LOG10E Numeric approximation to logarithm of e base 10 – approximately 0.43429.

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

SQRT2 Numeric approximation to the square root of 2, approximately 1.4142.

SQRT1_2 Numeric approximation to the square root of ½, approximately 0.7071.

Common Math Object Methodsabs(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.

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.

1. Constructor – customer1.constructorAny 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);

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 StringsStrings can be manipulated in a number of ways including:changing the casebreaking apart a string into smaller partsextracting 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:

A J a v a S c r i p t s t r i n g0 1 2 3 4 5 6 7 8 9 1

011

12

13

14

15

16

17

18

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 StringsThe formatting of strings is accomplished by using string methods such as:big() – increases the size of the textblink() – causes the text to blinkbold() – bolds the stringfontcolor() – changes the font color of the textfontsize() – changes the size of a fontitalics() – italicizes the textsmall() – decreases the size of the textstrike() – strikes through the textsub() – subscripts the textsup() – 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);

Lab

Step 1: <html> <head> <title> Practice Javascript </title>

<script type="text/javascript">// Insert your code here</script></head><body>

</body></html>

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

Recommended