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

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Formulas, Ranges, and Functions. Formulas n Formulas perform operations such as addition, multiplication, and comparison on worksheet values. n Formulas.
1 CS101 Introduction to Computing Lecture 41 Images & Animation (Web Development Lecture 14)
Session 8 JavaScript/Jscript: Objects Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
HTML Comprehensive Concepts and Techniques Second Edition Project 8 Integrating JavaScript with HTML.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
Tutorial 11 Working with Operators and Expressions
Tutorial 14 Working with Forms and Regular Expressions.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
JavaScript Objects Objects – JavaScript is an object-based language Has built-in objects we will use – You can create your own objects We concentrating.
1 CS101 Introduction to Computing Lecture 29 Functions & Variable Scope (Web Development Lecture 10)
1 CS101 Introduction to Computing Lecture 38 String Manipulations (Web Development Lecture 13)
CST JavaScript Validating Form Data with JavaScript.
JavaScript Events and Event Handlers 1 An event is an action that occurs within a Web browser or Web document. An event handler is a statement that tells.
XP Tutorial 14 New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
Using Object-Oriented JavaScript CST 200- JavaScript 4 –
Tutorial 14 Working with Forms and Regular Expressions.
Scripting Languages.
Chapter 3 : Processing on the Front End JavaScript Technically its name is ECMA-262, which refers to the international standard which defines it. The standard.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)
String Object.  Conundrum: I would like people to have more time on the revisions…  … but I don't have a lot of time myself for more grading  A1 Revision.
Chapter 8 Cookies And Security JavaScript, Third Edition.
JavaScript, Fourth Edition
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.
JavaScript For...In Statement The for...in statement loops through the elements of an array or through the properties of an object. Syntax for (variable.
JavaScript Functions & Objects. JavaScript Functions FunctionDescription decodeURI()Decodes an encoded URI decodeURIComponent()Decodes an encoded URI.
Objects.  Java Script is an OOP Language  So it allows you to make your own objects and make your own variable types  I will not be going over how.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
M. Taimoor Khan Javascript Objects  Every data-type defined in Javascript is an object  It has a class definition for.
Keeping it Neat: Functions and JavaScript Source Files Chapter 7.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Project 1: Using Arrays and Manipulating Strings Essentials for Design JavaScript Level Two Michael Brooks.
Pascal Programming Today Chapter 11 1 Chapter 11.
XP Tutorial 2 New Perspectives on JavaScript, Comprehensive1 Working with Operators and Expressions Creating a New Year’s Day Countdown Clock.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Working with Loops, Conditional Statements, and Arrays.
Unit 10-JavaScript Functions Instructor: Brent Presley.
XP Tutorial 7 New Perspectives on JavaScript, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
Tutorial 11 1 JavaScript Operators and Expressions.
Project 4: Working with Variables Essentials for Design JavaScript Level One Michael Brooks.
XP Tutorial 3 New Perspectives on JavaScript, Comprehensive1 Working with Arrays, Loops, and Conditional Statements Creating a Monthly Calendar.
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming javascript arrays.
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
JavaScript and Ajax (JavaScript Arrays) Week 5 Web site:
Strings Robin Burke IT 130. Outline Objects Strings methods properties Basic methods Form validation.
Review Objects – data fields – constructors – Methods Classes.
Chapter 5 Murach's JavaScript and jQuery, C1© 2012, Mike Murach & Associates, Inc.Slide 1.
JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
Introduction to Calculated Columns Variables, Conditionals, and String Manipulation PRESENTER: Cameron Blashka| Informer Implementation Specialist| April.
>> Introduction to JavaScript
Containers and Lists CIS 40 – Introduction to Programming in Python
Basics of JavaScript Programming Language
SEEM4570 Tutorial 05: JavaScript as OOP
Java Script.
Scope, Objects, Strings, Numbers
Objectives Create an array Work with array properties and methods
Perl Variables: Array Web Programming.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

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 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 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;

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

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 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(“; "));

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(", "));

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(); Example of : July 4, 2004: 6:25:22 July 4, ,7,4

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

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 // 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(" Current date: "+dayNames[dayOfTheWeek]+" "+day+" "+monthNames[month]+" "+year); document.write(" Current time: "+hours+":"+minutes+":"+seconds);

More example with Date object Customizing the Date object with prototype property 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 ENumeric approximation to Euler’s constant e - approximately LN10Numeric approximation to natural logarithm of 10 – approximately LN2Numeric approximation to natural logarithm of 2 – approximately LOG10ENumeric approximation to logarithm of e base 10 – approximately LOG2ENumeric approximation to logarithm of e base 2 – approximately PI Numeric approximation to , the ratio of a circle’s circumference to its diameter – approximately SQRT2Numeric approximation to the square root of 2, approximately SQRT1_2Numeric approximation to the square root of ½, approximately

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.

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

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()+" ");

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 ”

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 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. "); }

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. "); }

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);

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. "); }

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. "); }

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

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

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";

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."); }

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 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(" ");

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:

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;

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:

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 "; var customerLname = customer1.substring(0,29); var customerFname = customer1.substring(29,39); var customerPhone = customer1.substring(39,47);

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

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