0% found this document useful (0 votes)
5K views

Misy233 CH4

algorithme and programming notes

Uploaded by

christbiese11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5K views

Misy233 CH4

algorithme and programming notes

Uploaded by

christbiese11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

MISY233

CHAPTER 4
4.1 Overview of JavaScript

• Originally developed by Netscape, as LiveScript

• Became a joint venture of Netscape and Sun in 1995, renamed JavaScript

• Now standardized by the European Computer Manufacturers Association


as ECMA-262 (also ISO 16262)
• MS alternative : JScript

• We’ll call collections of JavaScript code scripts, not programs. The parts are
• Core : Operators, expressions, statements and subprograms
• ClientSide : Objects to support HTML (What our course covers)
• ServerSide : Objects to support server, DB Management etc.
4.1 Overview of JavaScript (cont.)

• JavaScript and Java are only related through syntax


• JavaScript is dynamically typed (No need to define variables)
• JavaScript’s support for objects is very different

• Javascript does not suport Object Orientation

• JavaScript is the primary language for Ajax


• Async. Javascript and XML: Send/Receive data to/from server async.

• User interactions through forms are easy

• The Document Object Model makes it possible to support dynamic HTML documents
with JavaScript, allowing it to access and modify CSS properties and contents
4.2 Object Orientation and JavaScript

• JavaScript is NOT an object-oriented programming language


• Does not support class-based inheritance
• Cannot support polymorphism
• Has prototype-based inheritance, which is much different (and out of course)
• JavaScript objects are collections of properties, which are like the
members of classes in Java and C++
• JavaScript has primitives for simple types
• The root object in JavaScript is Object : All objects are derived
from Object. Has Methods bıt no data properties
• All JavaScript objects are accessed through references
4.3 General Syntactic Characteristics

• For this course, all JavaScript scripts will be embedded in HTML


documents

• Either directly, as in
<script type = "text/javaScript">
--JavaScript script –
</script>

• Or indirectly, as a file specified in the src attribute of <script>, as in


<script type = "text/javaScript"
src = "myScript.js">
</script>
4.3 General Syntactic Characteristics (cont.)

• Language Basics:

• Identifier form: begin with a letter or underscore, followed by any number of


letters, underscores, and digits
• Case sensitive
• 25 reserved words, plus future reserved words
• Loops, Definitions, Control statements etc.
• Comments: both //and /* … */
• Scripts are usually hidden from browsers that do not include JavaScript
interpreters by putting them in special comments
<!--
--JavaScript script –
//-->
• Also required by the XHTML validator
4.3 General Syntactic Characteristics (cont.)

• Language Basics: (cont.)

• Semicolons can be a problem

• They are “somewhat” optional

• Problem: When the end of the line can be the end of a statement – JavaScript
puts a semicolon there
• Solution : Put every statement on its own line and terminate with “;”
4.4 Primitives, Operations, & Expressions

• All primitive values have one of the five primitive types: Number, String,
Boolean, Undefined, or Null
• Number, String, and Boolean have wrapper objects (Number, String,
and Boolean)
• In the cases of Number and String, primitive values and objects are
coerced back and forth so that primitive values can be treated essentially
as if they were objects
• Numeric literals – just like Java
• All numeric values are stored in double-precision floating point
• String literals are delimited by either ' or “
• Can include escape sequences (e.g., \t)
• All String literals are primitive values
• Eg. ' You are here ' is the same as ' You'\re here '
4.4 Primitives, Operations, & Expressions (cont.)

• Boolean values are true and false


• The only Null value is null
• The only Undefined value is undefined
• JavaScript is dynamically typed –any variable can be used for anything
(primitive value or reference to any object)
• The interpreter determines the type of a particular occurrence of a variable
• Variables can be either implicitly (by assigning value before declaration) or
explicitly (by declaring it before usage) declared. Recommended method is
declaration prior to usage.
let sum = 0;
today = "Monday";
flag = false;
4.4 Primitives, Operations, & Expressions (cont.)

• Numeric operators : ++, --, +, -, *, /, %


• All operations are in double precision
• Same precedence and associativity as Java

Example : When a = 7
(++a) * 3 = 24, and a = 8
(a++) * 3 = 21, and a = 8

• The MathObject provides floor, round, max, min, trig functions, etc.
• e.g., Math.cos(x)
Example : Math.round(1.6) returns 2 (rounds to nearest
int)
Math.round(-1.6) returns -2
Math.floor(1.6) returns 1 (Downs to nearest int)
Math.floor(-1.6) returns -2
4.4 Primitives, Operations, & Expressions (cont.)

• The Number Object


• Some useful properties: MAX_VALUE, MIN_VALUE, NaN,
POSITIVE_INFINITY, NEGATIVE_INFINITY, PI
• e.g., Number.MAX_VALUE
• An arithmetic operation that creates overflow returns NaN (Not A Number)

• NaN is not == to any number, not even itself

• Test for it with isNaN(x)

• Number object has the method, toString


4.4 Primitives, Operations, & Expressions (cont.)

• String catenation operator-+


• Coercions (Conversions)
• Catenation coerces numbers to strings
• Numeric operators (other than +) coerce strings to numbers (if either operand of +is a string, it is
assumed to be catenation)
• Conversions from strings to numbers that do not work return NaN
• Explicit conversions
• 1. Use the String and Number constructors
• 2. Use toString method of numbers
• 3. Use parseInt and parseFloaton strings
• String properties & methods:
• Length e.g., var len = str1.length; (a property)
• charAt (position) e.g., str.charAt(3)
• indexOf (string) e.g., str.indexOf('B') //Find location
• Substring (from, to) e.g., str.substring(1, 3)
• toLowerCase() e.g., str.toLowerCase()
• toUpperCase() e.g., str.toUpperCase()
4.4 Primitives, Operations, & Expressions (cont.)

• The typeof operator Returns


• "number", "string", or "boolean" for Number, String, or
Boolean,
• "undefined" for Undefined,
• "function" for functions, and
• "object" for objects and NULL
• Assignment statements – just like C++ and Java
a = a + 7; is same as a += 7;
4.4 Primitives, Operations, & Expressions (cont.)

• The Date Object


• Create one with the Date constructor (no params)

Var today = new Date();

• Local time methods of Date:


toLocaleString – returns a string of the date
getDate – returns the day of the month
getMonth – returns the month of the year (0 –11)
getDay – returns the day of the week (0 –6)
getFullYear – returns the year
getTime – returns the number of milliseconds since January 1, 1970 (WHY ?)
getHours – returns the hour (0 –23)
getMinutes – returns the minutes (0 –59)
getMilliseconds – returns the millisecond (0 –999)
4.4 Screen Output & Keyboard Input

• The JavaScript model for the HTML document is the Document object
• The model for the browser display window is the Window object
• The Window object has two properties, document and window, which refer
to the Document and Window objects, respectively
• The Document object has a method, write, which dynamically
creates content
• The parameter is a string, often catenated from parts, some of which are
variables
e.g., document.write("Answer: " + result + "<br />");
• The parameter is sent to the browser, so it can be anything that can
appear in an HTML document (<br />, but not \n)
• The Windowobject has three methods for creating dialog boxes :
alert, confirm, and prompt
4.4 Screen Output & Keyboard Input (cont.)

• 1. alert("Hey! \n");
• Parameter is plain text, not HTML
• Opens a dialog box which displays the parameter string and an OK button
• It waits for the user to press the OK button
• 2. confirm("Do you want to continue?");
• Opens a dialog box and displays the parameter and two buttons, OK and
Cancel
• Returns a Boolean value, depending on which button was pressed (it waits for
one)
• 3. prompt("What is your name?", "");
• Opens a dialog box and displays its string parameter, along with a text box and
two buttons, OK and Cancel
• The second parameter is for a default response if the user presses OK without
typing a response in the text box (waits for OK)
4.6 Control Statements

• Similar to C, Java, and C++


• Compound statements are delimited by braces, but compound statements
are not blocks
• Control expressions – three kinds
• 1. Primitive values
• If it is a string, it is true unless it is empty or "0"
• If it is a number, it is true unless it is zero
• 2. Relational Expressions
• The usual six: ==, !=, <, >, <=, >=
• Operands are coerced (forced to change) if necessary
• If one is a string and one is a number, it attempts to convert the string to a number
• If one is Boolean and the other is not, the Boolean operand is coerced to a number (1 or 0)
• The unusual two: ===and !==
• Same as ==and !=, except that no coercions are done (operands must be identical)
• Comparisons of references to objects are not useful (addresses are compared, not values)
4.6 Control Statements (cont.)

• Control expressions – three kinds (cont.)


• 3. Compound Expressions
• The usual operators: &&, ||, and !
• The Boolean object has a method, toString, to allow them to be printed (true or false)
• If a Boolean object is used in a conditional expression, it is false only if it is null or
undefined
• Selection Statements
• The usual if-then-else (clauses can be either single statements or compound
statements)
4.6 Control Statements (cont.)

• Switch
switch (expression) {
case value_1:
// value_1 statements
case value_2:
// value_2 statements

[default:
// default statements]
}
• The statements can be either statement sequences or compound statements
• The control expression can be a number, a string, or a Boolean
• Different cases can have values of different types
4.6 Control Statements (cont.)

• Loop statements
while (control_expression)
{ statement(s) or command(s) }

for (init; control; increment)


{ statement(s) or command(s) }

• init can have declarations, but the scope of such variables is the whole script

Example :
for(count=0; count =<10; count++) { sum += count }

do { statement(s) or command(s) }
while (control_expression)
4.7 Object Creation and Modification

• Objects can be created with new


• The most basic object is one that uses the Object constructor, as in

let myObject = new Object();


• The new object has no properties - a blank object
• Properties can be added to an object, any time
let myAirplane = new Object();
myAirplane.make = "Cessna";
myAirplane.model = "Centurian";
• Objects can be nested, so a property could be itself another object,
created with new
4.7 Object Creation and Modification (cont.)

• Properties can be accessed by dot notation or in array notation, as in

let property1 = myAirplane["model"];


let property1 = myAirplane.model;

• Deleting properties
delete myAirplane.model;

• Another Loop Statement (an iterator)


• for (identifier in object) statement or compound

for (let prop in myAirplane)


document.write(myAirplane[prop] + "<br />");
4.8 Arrays

• Objects with some special functionality


• Array elements can be primitive values or references to other objects
• Length is dynamic -the length property stores the length
• Array objects can be created in two ways, with new, or by assigning an array literal
let myList = new Array(24, "bread", true);
let myList2 = [24, "bread", true];
let myList3 = new Array(24);
• The length of an array is the highest subscript to which an element has been assigned, plus
1. The ones in-between are also created.
myList[122] = "bitsy"; // length is 123
• Because the lengthproperty is writeable, you can set it to make the array any length you
like, as in
myList.length = 150;
• Assigning a value to an element that does not exist creates that element
4.8 Arrays (cont.)

• Array methods:
• Join // Converts array into a single string value
e.g., let listStr = [“Paris”, “Rome”];
let listStr = list.join(", "); // Becomes
“Paris,Rome”

• Reverse // Seperates the joined strings

• Sort – e.g.,names.sort();
• Coerces elements to strings and puts them in alphabetical order

• Concat // Adds some elements to an existing array and creates a new one
e.g. newList = listname.concat(47, 26);
4.8 Arrays (cont.)

• Array methods:
• Slice(a,b) // returns elements starting from a, up to (and
not inclusive) to b
listPart = list.slice(2, 5); // retrieves 2nd, 3rd and 4th
listPart2 = list.slice(2); // retrieves 2nd and all the rest

• toString
• Coerce elements to strings, if necessary, and catenate them together, separated by commas (exactly
like join(", "))

• push, pop
• Removes/adds elements to/from the end of an array

• unshift, and shift


• Removes/adds elements to/from the beginning of an array
4.9 Functions

• Function function_name([formal_parameters]) { --body – }


• Return value is the parameter of return
• If there is no return, or if the end of the function is reached, undefined is returned
• If return has no parameter, undefined is returned
• Functions are objects, so variables that reference them can be treated as other object
references
• If fun is the name of a function, both the notations below can be used to execute it
ref_fun = fun;
...
ref_fun(); /* A call to fun */
• We place all function definitions in the head of the the HTML5 document
• All variables that are either implicitly declared or explicitly declared outside functions are
global
• Variables explicitly declared in a function are local
• If same variable name is used in global and local scope, local one has precedence.
4.9 Functions (cont.)

• Parameters are passed by value, but when a reference variable is passed, the semantics
are pass-by-reference. Arrays can also be passed.
• There is no type checking of parameters, nor is the number of parameters checked
(excess actual parameters are ignored, excess formal parameters are set to undefined)
• All parameters are sent through a property array, arguments, which has the length
property
• There is no clean way to send a primitive by reference
• One dirty way is to put the value in an array and send the array’s name
function by10(a) { a[0] *= 10; }
...
let listx = new Array(1);
...
listx[0] = x;
by10(listx);
x = listx[0];
4.9 Functions (cont.)

• To sort something other than strings into alphabetical order, write a


function that performs the comparison and send it to the sort
method
• The comparison function must return a negative number, zero, or a positive
number to indicate whether the order is ok, equal, or not
function num_order(a, b) {return a -b;}
• Now, we can sort an array named num_list with:
num_list.sort(num_order);
• Functions can be used to create properties and methods
• Example :
Var customers = new Array[“John”,”James”]
• The “Array” is a reference variable of constructors (Next Slide)
4.10 4.11 Constructors

• Used to initialize objects, but actually create the properties


function plane(newMake, newModel, newYear) {
this.make = newMake;
this.model = newModel;
this.year = newYear; }
myPlane = new plane("Cessna", "Centurian", "1970");
• Can also have method properties // How to use functions to serve as a method
function displayPlane() {
document.write("Make: ", this.make, "<br />");
document.write("Model: ", this.model, "<br />");
document.write("Year: ", this.year, "<br />"); }
• Now add the following to the constructor:
this.display = displayPlane;
4.11 Pattern Matching

• JavaScript provides two ways to do pattern matching based on regular


expressions:
1. Using RegEx objects (Out of the scope of this course)
2. Using methods on String objects

• Simple patterns : Two categories of characters in patterns:


• a. normal characters (match themselves)
• b. metacharacters (can have special meanings in patterns--do not match
themselves)
\| ( ) [ ] { } ^ $ * + ? .
• A metacharacter is treated as a normal character if it is backslashed
• period is a special meta character – it matches any character except newline
/3\.4/ matches 3.4
4.11 Pattern Matching (cont.)

• search(pattern) // as a method
• Returns the position in the object string of the pattern (position is relative to zero); returns -1 if it
fails
let str = "Gluckenheimer";
let position = str.search(/n/);
/* position is now 6 */

• Character classes
• Put a sequence of characters in brackets, and it defines a set of characters, any one of which matches
[abcd]
• Dashes can be used to specify spans of characters in a class
[a-z]
• A caret at the left end of a class definition means the opposite
[^0-9] // Matches any character except numbers
[^aei] // Matches any character except a, e, i
4.11 Pattern Matching (cont.)

• Character classes (continued)


• Character class abbreviations

Abbr. Equiv. PatternMatches


\d [0-9] a digit
\D [^0-9] not a digit
\w [A-Za-z_0-9] a word character
\W [^A-Za-z_0-9] not a word character
\s [ \r\t\n\f] a whitespace character
\S [^ \r\t\n\f] not a whitespace character
4.11 Pattern Matching (cont.)

• Quantifiers

• Quantifiers in braces or between slashes

Quantifier Meaning
{n} exactly n repetitions
{m,} at least m repetitions
{m,n} at least m but not more than n repetitions
/xy{4}z/ xyyyyz
4.11 Pattern Matching (cont.)

• Quantifiers

• Other quantifiers (just abbreviations for the most commonly used quantifiers)

• * means zero or more repetitions


e.g., \d* means zero or more digits

• + means one or more repetitions


e.g., \d+ means one or more digits

• ? Means zero or one


e.g., \d? means zero or one digit
4.11 Pattern Matching (cont.)

• Anchors
• The pattern can be forced to match only at the left end with ^; at the end
with $
e.g.,
/^Lee/
matches "Lee Ann“ but not "Mary Lee Ann"
/Lee Ann$/
matches "Mary Lee Ann",
but not "Mary Lee Ann is nice“

• The anchor operators (^ and $) do not match characters in the string


-- they match positions, at the beginning or end
4.11 Pattern Matching (cont.)

• Pattern modifiers

• The i modifier tells the matcher to ignore the case of letters


/oak/i matches "OAK" and "Oak" and …

• The x modifier tells the matcher to ignore whitespace in the pattern


(allows comments in patterns)
4.11 Pattern Matching (cont.)

• Other Pattern Matching Methods of String


replace (pattern, string)

• Finds a substring that matches the pattern and replaces it with the string (g
modifier can be used)

let str = "Some rabbits are rabid";


str.replace(/rab/g, "tim");

str is now "Some timbits are timid"


4.11 Pattern Matching (cont.)

• Other Pattern Matching Methods of String (cont.)


match (pattern)
• The most general pattern-matching method
• Returns an array of results of the pattern-matching operation
• With the g modifier, it returns an array of the substrings that matched
• Without the g modifier, first element of the returned array has the matched
substring, the other elements have the values of $1, …
let str = "My 3 kings beat your 2 aces";
let matches = str.match(/[ab]/g);
Matches is set to ["b", "a", "a"]
4.11 Pattern Matching (cont.)

• Other Pattern Matching Methods of String (cont.)


split (parameter)
"," and /,/ both work

Example :
var str = "grapes:apples:oranges";
var fruit = str.split(":");
Fruits is not set to [grapes,apples,oranges]
4.12 Debugging JavaScript (Browser dependent)

• Programs create and display messages when errors occur, together with
some descriptions. Scripts, however, displays blank pages or
documents.

• MS IE v.8+
• A script error causes a small window to be opened with an explanation of the
error

• Firefox v.3+
• Select Tools and Error Console
• A small window appears to display script errors
• Remember to Clear the console after using an error message – avoids
confusion

You might also like