javascript basics chapter 4 of text supplement most of the text and my examples are in a directory...

110
JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at http://employees.oneonta.edu/higgindm/javascript/scriptexa mples.html Text examples are in http://.../Higgindm/csci245/javascript as js or html under their text names

Upload: lizbeth-rodgers

Post on 17-Jan-2018

245 views

Category:

Documents


0 download

DESCRIPTION

Parts of JavaScript Core: operators, expressions, statements and subprograms Client-side: browser control and user interaction (ie., mouse-clicks, input) Server-side: language features for use on a server – not covered in this text.

TRANSCRIPT

Page 1: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

JavaScript basics

Chapter 4 of text supplementMost of the text and

my examples are in a directory mostly linked at http://employees.oneonta.edu/higgindm/javascript/scriptexamples.html

Text examples are inhttp://.../Higgindm/csci245/javascript as js or html under their text names

Page 2: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

background

• JavaScript was originally called LiveScript (pre-’95) and was developed by Netscape. It changed its name to JavaScript and became a joint venture with Sun. ECMA developed a standard for JavaScript in the late 90s which is also an ISO standard and the official name of the language is ECMAScript. ECMA is at version 3 which corresponds to Netscape’s 1.5.

Page 3: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Parts of JavaScript

• Core: operators, expressions, statements and subprograms

• Client-side: browser control and user interaction (ie., mouse-clicks, input)

• Server-side: language features for use on a server – not covered in this text.

Page 4: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Client-side JavaScript• XHTML-embedded scripting language.• Client-side JavaScript can substitute for some server-side

functionality – especially things like checking form data to make sure phone numbers have an area code or ss numbers have the right format.

• The browser interprets the JavaScript.• Client-side JavaScript cannot substitute for server-side file

networking and database operations.• Applets – which are also client-side code (albeit delivered as byte-

code to a client by a server) can often be replaced by JavaScript.• Since Applets can access nearly the full java API(s) they are much

more powerful than JavaScript, but also harder to learn.

Page 5: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

interaction

• Mouseclicks and form data can trigger java script functions.

• DOM allows JavaScript to access and modify the CSS properties and content of any element of a displayed XHTML – enabling dynamic presentation. (this is covered in text chapter 6)

Page 6: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

interpreter

• Browsers use their JavaScript interpreters to process scripts embedded in html.

• Client-side input data checking is an important role for JavaScript. Without this, form information goes to the server, which must locate errors and relay them back to the client.

Page 7: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Placement in head or body of html

• Typically function definitions or code for handling events is placed in the head (and accessed if/as needed).

• Script meant to be processed just once as part of document content goes in the body. Scripts in the head are cataloged but not interpreted at that time. Scripts in the body are processed as encountered.

Page 8: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

OO

• javaScript is not OO, but Object based. There are no classes, polymorphism or object inheritance.

• It does support something called prototype-based inheritance.

• However, documents and elements are modeled with objects and so there is an object-sense to JavaScript.

Page 9: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

objects

• JavaScript objects are collections of properties, roughly corresponding to C++ or Java objects. Each is a data or method property. Data properties may be primitives or references, although in JavaScript the latter are themselves usually called Objects.

• The text will usually use properties to mean data properties and methods to mean method properties.

Page 10: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Reserved words

break delete function Return typeof

case do if switch var

catch else in this void

continue finally instanceof throw while

default for new try with

Page 11: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

More about reserved words• Look at http://www.ecma.ch to see a list of future

reserved words.• Also some predefined words: alert, open, self,

java• // on a line signals comment to end• C++/Java multiline comment syntax: /*…*/• Most browsers now do recognize JavaScript so

placing script in special comments is less important, except it may cause validation problems for XHTML validators if the JavaScript includes recognized tags like <br/>

Page 12: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

So…

• Use the usual comment introduction for scripts

• You must close script with java/c++ comment on its own line followed by end of XHTML comment:

• <!--• Put JS here• // -->

Page 13: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

(skipping down in text ppt)Conversions

• In the expression 7*”3” • JavaScript would try (and succeed) in

converting “3” to 3 and perform the arithmetic because * is a numeric operator.

• If “3” were replaced by “Bob” the result would be NaN

Page 14: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

output to the html document• Document.write(“here is your answer”,answer,”<br/>”);• Basically writes (dynamic) html content

Page 15: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

A really simple script<html><body>usual content<script type="text/javascript"><!--var answer=1234;document.write("<br/>here is

your answer",answer,"<br/>");//now end script// --></script>more usual html content</body></html>

Page 16: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

the earlier example using an alert instead of document.write(..)

<html><body>usual content<script type="text/javascript"><!--var answer=1234;alert("here is your answer: " +answer);// --></script>more usual html content</body></html>

Page 17: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

First the alert, then the page

Page 18: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Some more examples• http://employees.oneonta.edu/higgindm/javascript/AddN

umsEx.html• http://employees.oneonta.edu/higgindm/javascript/scripte

xamples.html• (many of my examples and code posted there)• http://employees.oneonta.edu/Higgindm/javascript/basec

onverterEx2.html• http://employees.oneonta.edu/Higgindm/javascript/dialog

boxEx.html

Page 19: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Aside on two operators: “strict” comparison

• === and !== disallow type conversions in evaluation.

• The usual == and != allow type conversions of operands, so “3”==3 evaluates to true.

• === disallows type conversions so 3===“3” evaluates to false.

Page 20: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Text pg 149 quadratic roots<html><body><script type = "text/javascript"><!--// Get the coefficients of the equation from the uservar a = prompt("What is the value of 'a'? \n", "");var b = prompt("What is the value of 'b'? \n", "");var c = prompt("What is the value of 'c'? \n", "");// Compute the square root and denominator of the resultvar root_part = Math.sqrt(b * b - 4.0 * a * c);var denom = 2.0 * a;// Compute and display the two rootsvar root1 = (-b + root_part) / denom;var root2 = (-b - root_part) / denom;document.write("The first root is: ", root1, "<br />");document.write("The second root is: ", root2, "<br />");// --></script></body></html>

Page 21: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Previous html, first prompts for coefficients a,b,c

Page 22: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Borders2.html: javascript prompts for table borders enhances html display

Page 23: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

borders2 uses switch statement<body><script type = "text/javascript"><!--var bordersize;bordersize = prompt("Select a table border size \n" + "0 (no border) \n" + "1 (1 pixel border) \n" + "4 (4 pixel border) \n" + "8 (8 pixel border) \n");

switch (bordersize) {case "0": document.write("<table>"); break;case "1": document.write("<table border = '1'>"); break;case "4": document.write("<table border = '4'>"); break;case "8": document.write("<table border = '8'>"); break;default: document.write("Error - invalid choice: ", bordersize, "<br />");}

Page 24: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

More of borders2document.write("<caption> 2001 NFL Divisional Winners </caption>");document.write("<tr>","<th />","<th> American Conference </th>","<th> National Conference </th>","</tr>","<tr>","<th> East </th>","<td> New England Patriots </td>","<td> Philadelphia Eagles </td>","</tr>","<tr>","<th> Central </th>","<td> Pittsburgh Steelers </td>","<td> Chicago Bears </td>","</tr>","<tr>","<th> West </th>","<td> Oakland Raiders </td>","<td> St. Louis Cardinals </td>","</tr>","</table>");// --></script></body></html>

Page 25: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Date functions

Page 26: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Javascript for first part of date <script type="text/javascript"><!--var today=new Date();var dates=today.toLocaleString();var day=today.getDay();var month=today.getMonth();var year=today.getFullYear();var timeMillis=today.getTime();var hour=today.getHours();var minute=today.getMinutes();var seconds=today.getSeconds();var millis=today.getMilliseconds();document.write("Date:" + dates + "<br/>","Day:" + day + "<br/>","Month:" + month + "<br/>","Year:" + year + "<br/>","Time Millis:" + timeMillis + "<br/>","Hour:" + hour + "<br/>","Minute:" + minute + "<br/>","Second:" + seconds + "<br/>","Millis:" + millis + "<br/>");// --></script>

Page 27: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

insert code for loop timervar start=new Date();var product=1.00001;//add a loopfor(var count=0;count<10000;count++) product=product+1.00001*1.0002-

1.000008888/1.0001;var end=new Date();var diff=end.getTime()-start.getTime();document.write("<br/>loop took" + diff+"millis");

Page 28: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Control examples

• Text examples borders.html and date.html show switch and for statements.

• JavaScript supports if and if…else, also while and do…while loops with java/c++ syntax.

Page 29: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

while loop example<script type = "text/javascript"><!--// whose factorial do you want?var a = prompt("Whose factorial?\n", "");// Compute the factorialvar fact= 1;//multiplicative identityvar ctr=1;while(ctr<=a){fact=fact*ctr;ctr++;}document.write("The factorial of ", a, " is ");document.write( fact, "<br />");// --></script>

Page 30: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Factorials using while

Page 31: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Fib numbers using while loop

Page 32: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Entered 34 and 23

Page 33: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Larger of 2 ints<script type = "text/javascript"><!--// var x = prompt("first?\n", "");var y = prompt("second?\n", "");//convert to numbers….var a=Number(x);var b=Number(y);// Compute the orderingvar big;var small;if (a>b){big=a;}else {big=b;}small=big==a?b:a;

document.write("The bigger is", big, "the smaller ");document.write( small, "<br />");// --></script>

Page 34: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Fixed previous to handle numbers

Page 35: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

another version<script type = "text/javascript"><!--var a = prompt("first?\n", "");var b = prompt("second?\n", "");// Compute the ordering for stringsvar x=parseInt(a);var y=parseInt(b);var big;var small;if (a>b){big=a;}else {big=b;}small=big==a?b:a;document.write("The bigger string is", big, "the smaller string is");document.write( small, "<br />");// Compute the ordering for intsif (x>y){big=x;}else {big=y;}small=big==x?y:x;document.write("The bigger int is", big, "the smaller int is");document.write( small, "<br />");// -->

Page 36: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Lab 1 for javascript

• Expand the previous example. The user enters 3 integers via prompts, display them in descending order.

Page 37: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Objects• Objects can be created with the new keyword

and call to a constructor as invar obj=new Object();• The created object here has no initial properties.• Properties themselves can be objects, (or not),

accessible via the dot or [] operator, as invar theprop=airplane.engine;//or var theprop=airplane[engine];

• The next slide shows how to set and display some properties.

Page 38: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Displaying properties of an object in a loop<script type = "text/javascript"><!--var myAirplane = new Object(); myAirplane.make = "Cessna"; myAirplane.model = "Centurian";myAirplane.horsepower="245hp";myAirplane.seating=6;myAirplane.color="blue"; document.write("<p><b>The properties of airplane list

is:</b> ", "<br />");for (var prop in myAirplane) document.write(myAirplane[prop] + "<br />"); document.write("</p>");// --></script>

Page 39: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Csci245/javascript/airplaneprops.html

Page 40: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Arrays• Arrays are dynamically allocated from the heap

in JavaScript• Only the locations actually assigned values

occupy space in memory, despite array length.• Length is a R/W “property” so it can be set, and

retrieved.myarray.length=100myarray.length=44• is a legal sequence. 44 would be length though

there might not actually be anything allocated.

Page 41: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Arrays…text example: insert names<body><script type = "text/javascript"><!--// The original list of namesvar name_list = new Array("Al", "Betty", "Kasper", "Michael", "Roberto", "Zimbo");var new_name, index, last;// Loop to get a new name and insert itwhile (new_name = prompt("Please type a new name", "")) {// Loop to find the place for the new name last = name_list.length - 1; while (last >= 0 && name_list[last] > new_name) { name_list[last + 1] = name_list[last]; last--; }// Insert the new name into its spot in the array name_list[last + 1] = new_name;// Display the new array document.write("<p><b>The new name list is:</b> ", "<br />"); for (index = 0; index < name_list.length; index++) document.write(name_list[index], "<br />"); document.write("</p>");} //** end of the outer while loop// --></script></body>

Page 42: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Inserting names…prompt

Page 43: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Csci245/sebesta/Insert_names.html

Page 44: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

In case of errors in Firefox

• Mozilla already provides some help in a javascript console in the tools menu.

Page 45: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Debugging for JavaScript in Firefox

• If you have your own machine, download firebug, a plugin for Firefox very helpful in debugging javascript (which will include the js libraries like Backbone and jQuery).

Page 46: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Firebug session

Page 47: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

For IE

• Go into tools/internet options/advanced tab and check/uncheck boxes as in next slide.

Page 48: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

For IE

Page 49: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

plunker

• There are several javascript debugger/tester thingies out there. Plunker is one.

Page 50: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Go to http://plnkr.co/edit/?p=catalogue

Page 51: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Array size is very dynamic: “add” two arrays together

Higgindm/csci245/javascript/expand_names.htmlHere I simply add an array to the (unallocated) space at the end of another:

var name_list1 = new Array("Al", "Betty", "Kasper", "Michael", "Roberto", "Zimbo");var name_list2 = new Array("Alley", "Bettyboop", "Kaspertheghost", "MichaelRow the boat", "Roberto Gonzales", "ZimboZambo");var new_name, index, last;var len2=name_list2.length;for (index = 0; index < name_list1.length; index++) name_list2[len2+index]=name_list1[index]; document.write("<p><b>The new name list is:</b> ", "<br />"); for (index = 0; index < name_list2.length; index++) document.write(name_list2[index], "<br />"); document.write("</p>");

Page 52: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

/csci245/javascript/expand_names.html

Page 53: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

More methods: join

• Array.join(..) converts array contents to string and returns the string concatenation of them. Without any parameter, it puts a “,” between elements. You can pass another separator.

Page 54: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

concat

• Array.concat(…) concatenates its parameters to the end of the array (increasing allocation and array length)

Page 55: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Sort we have seen in examples above

• Sort converts contents to string and provides dictionary ordering.

• A different comparison function can be provided (returning – for less, 0 for equal and + for greater, as in C) to sort contents differently.

function f(a,b){return a-b;} • provides numerical ordering

Page 56: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Slice works like substring

• Slice returns an array subset of the original from the start param position to the final position -1. If only 1 param is provided, it returns from that position to the end of the array.

Little=Big.slice(4,7); • would return an array of 3 guys, from

positions 4, 5 and 6 of Big

Page 57: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Push and pop

• These modify at the highest subscript of the array allowing stack operations

Page 58: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Postfix expression evaluation

• We are used to writing expressions in infix form, where the operator appears between its operand. For example 10+20 is an infix expression.

• In postfix form, the operator appears after its operands. 10 20 + is legal postfix and corresponds to the infix above.

• Postfix expressions can be quite complicated: 10 20 + 30 + 40 - 50 * evaluates to 1000.

Page 59: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Script for postfix uses push and popvar x = prompt("enter a postfix expression"); var matches=x.match(/\S*/g)var postfix=new Array();var j=0;for(var i=0;i<matches.length;i++){ if(matches[i].length>0){ postfix[j++]=matches[i];}//if }//forvar stack=new Array();for (index = 0; index < postfix.length; index++){//for var c=postfix[index].charAt(0); if(c>='0' && c <='9'){ //process integer var num=Number(postfix[index]); stack.push(num); } else{//operator var right=stack.pop(); var left=stack.pop(); switch(c){ case '+':stack.push(left+right);break; case '-':stack.push(left-right);break; case '*':stack.push(left*right);break; case '/':stack.push(left/right);break; default:document.write(postfix[index], " error<br />"); }//switch }//else }//fordocument.write(stack[0], "<br />");

Page 60: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Embedded in html body and running

Page 61: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Evaluation of expression

Page 62: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Improvements needed

• My postfix evaluator currently requires blanks between input values but blanks should not be needed between operators, or between operators and operands.

• No error checking is present and no error messages are generated by illegal expressions. JavaScript will output NaN for certain kinds of numeric errors.

Page 63: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Shift and unshift

• These modify at the start/end of an array allowing queue operations.

• Exercise for Higgins… Do BFS or DFS using shift unshift

Page 64: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Nested/2d arrays<script type = "text/javascript"><!--var nested=[[1,2,3],[3,4,5],[5,6,7],[7,8,9]];for(var row=0;row<=3;row++){ document.write("Row",row,": "); for(var col=0;col<=2;col++) document.write(nested[row][col]," ");document.write("<br/>");}// --></script>

Page 65: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

nested arrays in firefox

Page 66: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Functions

• Define in <head> portion of html• May have local vars and params• Aside: Other variables declared in <head> are

treated as global.• Objects are passed by reference so if something

in the object reference is changed (in a function) then the object is changed when you return.

• Consequently, (as in Java), you need to be tricky to change a primitive in a function.

Page 67: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Text example…parameters <head><script type = "text/javascript">

// Function params// Parameters: two named parameters and one unnamed// parameter, all numbers// Returns: nothing function params(a, b) { document.write("Function params was passed ", arguments.length, " parameter(s) <br />"); document.write("Parameter values are: <br />"); for (var arg = 0; arg < arguments.length; arg++) document.write(arguments[arg], "<br />"); document.write("<br />"); } </script> </head> <body> <script type = "text/javascript">// A text driver for params params("Mozart"); params("Mozart", "Beethoven"); params("Mozart", "Beethoven", "Tchaikowsky"); </script>

Page 68: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

functions

Page 69: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

About array.sort• The array.sort method converts array contents to string

type and then sorts alphabetically.• To sort something other than strings into alphabetical

order, write a function that performs the comparison and send it to the sort method…

• See the median example in text.

Page 70: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

View at csci245/Javascript/medians.html: function definition

function median(list) { list.sort(function (a, b) {return a - b;}); var list_len = list.length;

// Use the modulus operator to determine whether// the array's length is odd or even// Use Math.floor to truncate numbers// Use Math.round to round numbers

if ((list_len % 2) == 1) return list[Math.floor(list_len / 2)]; else return Math.round((list[list_len / 2 - 1] +list[list_len / 2]) / 2); } // end of function median

Page 71: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Javascript/medians.html: in html body

<script type = "text/javascript">

var my_list_1 = [8, 3, 9, 1, 4, 7]; var my_list_2 = [10, -2, 0, 5, 3, 1, 7]; var med = median(my_list_1); document.write("Median of [", my_list_1, "] is: ",med ); med = median(my_list_2); document.write("Median of [", my_list_2, "] is: ",med,

"<br />");

</script>

Page 72: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Medians.html in firefox

Page 73: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

About constructors

• Constructors are special functions for constructing an instance of an object.

• In C++, Java and JavaScript: – the function has the same name as the object

it constructs– There is a predefined reference value this

which can be used to access the instance under construction

– No return statement

Page 74: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

text example fragment

• //build carfunction car(the_make, the_model,

the_year){//assuming these field namesthis.make=the_make;this.model=the_model;this.year=the_year;}

Page 75: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Expanded example: code in header<head><script type="text/javascript"><!--function car(tmake,tmodel,tyear){this.make=tmake;this.model=tmodel;this.year=tyear;this.display=showcar;//adding a method, too, to the object}function showcar(){document.write("car make=", this.make,"<br/>");document.write("car model=", this.model,"<br/>");document.write("car year=", this.year,"<br/>");}// --></script></head>

Page 76: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

In body<body><h1> all about cars </h1><script type="text/javascript"><!--var a=new Array(3);a[0]=prompt("enter make"); a[1]=prompt("enter model"); a[2]=prompt("enter year");var mycar=new car(a[0],a[1],a[2]);mycar.display();// --></script></body>

Page 77: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

After inputting data

Page 78: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Revising arg listfunction car(args){var tmake,tmod,tyr;tmake=tmod=tyr="not given";switch(arguments.length){case 3:tyr=arguments[2];case 2:tmod=arguments[1];case 1:tmake=arguments[0];case 0:}this.make=tmake;this.model=tmod;this.year=tyr;this.display=showcar;}

Page 79: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Jazzed up arg list

Page 80: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Adding more object methodsthis.price=baseprice;//add to car constructor in

//html head

function baseprice(){//also in html headswitch(this.make){ case"ford": return 10000; case "toyota": return 20000;}//switchreturn 15000;}//fn

//later... output in bodyvar num=mycar.price();//output in bodydocument.write("car cost=",num ,"<br/>");

Page 81: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

cost function

Page 82: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Pattern matching using regular expressions

• JavaScript provides strong pattern-matching capability based on the regular expressions of Perl.

• This is performed in one of two ways:– Using the RegExp object– Using methods of String object

• Our text covers only the latter type.

Page 83: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Character and Character-class patterns

• Characters are divided into “normal” and “meta-characters”

• Metacharacters have special meaning in building a character pattern.

• The metacharacters are \|()[]{}^$*+?.• Normal characters match themselves so

describing how they are used in building patterns is simple.

Page 84: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Character matching• The “search” method of the string class

provides the simplest way to match a pattern. It accepts a string argument and returns the position of this substring in the given string or -1 if it does not appear.

var str=“ this is a string”;var pos=str.search(/his/);if(pos>=0)document.write(“’his’ was found in

position”,pos,”<br/>”);else document.write(“’his’ was not found<br/>”);

Page 85: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Wildcard: the period

• Period is like a “wildcard” char, it matches anything except newline.

• The pattern /car./ would match “cars”, “carp”, “cart”, “car “, and so on.

• To match the period in a string you must use the backslash in front of the period so

• /3\.1412/ matches 3.1412• /3.1412/ also matches it, but it matches3X1412 as well.

Page 86: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Character classes

• Characters inside brackets define a “class” of characters, for example [abc] would match ‘a’ or ‘b’ or ‘c’

• A dash in a class definition indicates a sequence, so [a-h] would match any character ‘a’ up to ‘h’

• A circumflex inverts a class like taking the complement of a set. So the set [^aeiou] would match any character except lower case vowel.

Page 87: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Predefined classesName Equiv pattern matches

\d [0-9] digit

\D [^0-9] Not a digit

\w [A-za-z0-9] Alpha-numeric

\W [^A-Za-z0-9] Not alpha-numeric

\s [ \r\t\n\f] Whitespace char

\S [^ \r\t\n\f] Not a whitespace char

Page 88: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Some examples

• /\d\.\d\d/ matches digit, period then two digits, as in 3.14

• /\D\d\D/ matches a single digit character nested between non-digit chars.

• /\w\w\w/ matches three character alphanumeric

Page 89: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Repeating a character or a class in a pattern

• A quantifier in braces may be used to indicate how many occurrences of a char or a class must occur

• Ex• /xy{4}z/ matches xyyyyz• The symbolic quantifiers, *, + and ? can

also be used. * means 0 or more. + means one or more, ? means one or none.

Page 90: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

More examples

• /x*y+z?/ would match zero or more x’s followed by one or more y’s followed by zero or one z, as in /yyyyy/ and /xxxxyyyy/

and /xyz/

Page 91: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

using symbolic quantifiers with the named classes

• /\d+\.\d*/ one or more digits, a decimal point followed possibly by more digits.

• /[A-Za-z]\w*/ the way some programming languages name vars: an alphabetical char possibly followed by letters, digits and underscores.

• \b marks a word boundary

Page 92: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Lab exercises 1

• Get an SS# from the user in format xxx-xx-xxxx where all the xs are digits.• Get a phone number in the format (xxx)yxxx-xxxx where xs are digits and 0 or

1 blanks would be allowed where the y is.

Page 93: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Lab exercises 2

• Get a string from the user. See if it is a legal date in the format:

dd-mm-yyyy or dd/mm/yyyywhere mm can be 01 through 12, dd can be

01 through 31 and yyyy must be a year from 2000 through 2007

• Can you do better? Can you check that the number of days given is legal for the given month?

Page 94: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Project ideas• GPA calculator. • Allow user to enter any number of letter grades in this

format:X+ or X- or X (as detailed below)• A, B …E as the grade X, and where all grades are

allowed a + or – except A can’t have a plus and E can’t have a + or a -.

• Display the user’s (newly calculated) GPA each time a grade is entered, assuming all courses carry same credit hours.

• Harder: add a credit prompt as well and compute a weighted average GPA.

Page 95: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Anchors

• ^ at the start of a pattern means it must match at the start of the string and $ at the end of a pattern means it must match at the end of a string.

• /^pearl/ matches “pearls are pretty” but not “my pearls are pretty”

Page 96: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

anchors

• $ can be used to match just at the end • /back$/ would match “back” only at the

end of a string.• /gold$/ matches “I like gold” but not “gold

finger”• ^ and $ do not have special meaning

appearing elsewhere.

Page 97: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Pattern modifiers

• The letter i appearing after a pattern indicates it should match either upper or lower case so /apple/i would match “APPLE” or “aPpLe” for example.

• The x modifier means whitespace can appear

Page 98: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

More methods of the string class

• replace() can be used to replace substrings that match a given pattern.

• replace takes two parameters, the pattern and the replacement string.

Page 99: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Just the script…looking at beginning and end

var str="cat in the hat comes back";var pos1=str.search(/^cat/);var pos2=str.search(/cat$/);var pos3=str.search(/back$/);var pos4=str.search(/^back/);document.write("string is",str,"<br/>");if(pos1>=0)document.write("pos is ",pos1, " pattern matches:cat appears at

beginning","<br/>");if(pos2==-1)document.write("pattern does not match:cat not at end.","<br/>");if(pos3>=0)document.write("pos is ",pos3, " pattern matches:back appears at end","<br/>");if(pos4==-1)document.write("pattern does not match:back not at beginning","<br/>");

Page 100: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Running the script

Page 101: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

modifiers

• Special modifiers appearing after the pattern can provide added flexibility.

• i means upper or lower case.• x means whitespace in the pattern ok

Page 102: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Other useful string functions

• Replace can be used to replace substrings of the search string that match the pattern with another string. It takes two parameters: the pattern and the replacement. If the g modifier is attached to the pattern, it means all occurrences of the substring at to be replaced.

• Without the g, only the first occurrence is replaced.

Page 103: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Example1: global

var str ="every good boy deserves fudge";var newstr=str.replace(/er/g,"XXX");document.write(str,"<br/> ",newstr);

Page 104: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Example2 of globalsvar str ="every good boy deserves fudge";var newstr=str.replace(/e[rs]/g,"XXX");document.write(str,"<br/> ",newstr);

Page 105: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Match method• The match method is the most general. It

returns an array of contents of the string that matched the pattern.

var str ="my address is 239 Fitzelle, Oneonta 13820";

var matches=str.match(/\d/g);document.write(str,"<br/> ");for(var j=0;j<matches.length;j++) document.write(matches[j],"<br/> ");

Page 106: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at
Page 107: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

A more complicated example

var str ="my address is 239 Fitzelle, Oneonta 13820";

var matches=str.match(/(\d+)([^\d]+)(\d+)/);document.write(str,"<br/> ");for(var j=0;j<matches.length;j++) document.write(matches[j],"<br/> ");

Page 108: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

output

• Shows the match for the pattern, followed by the match for each parenthesized portion.

Page 109: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

A text examplefunction testnum(num)//look for area code{var ok=num.search(/\(\d{3}\)\d{3}-\d{4}/);if(ok==0)return true;return false;}function test(num)//from text…just look for number{var ok=num.search(/\d{3}-\d{4}/);if(ok>=0)return true;return false;}

Page 110: JavaScript basics Chapter 4 of text supplement Most of the text and my examples are in a directory mostly linked at

Checking phone numbers