javascript - piazza

14
JavaScript Elements JavaScript Interpreted programming language with OO capabilities Core syntax resembles C, C++ and JAVA However: Loosely typed - variables do not need to have a type specified JS Objects are more like hash tables or associative arrays than they are like structs (C) or objects (C++, Java) OO inheritance is prototype-based Draws inspiration from Perl in regular expressions and array- handling features 2 3 http://www.ecma-international.org/publications/standards/Ecma-262.htm 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) We’ll call collections of JavaScript code scripts, not programs Overview of JavaScript JavaScript can be used to: replace some of what is typically done with applets (except graphics) replace some of what is done with CGI - namely server-side programming (but no file operations or networking) User interactions through forms are easy The Document Object Model makes it possible to support dynamic HTML documents with JavaScript Much of what we will do with JavaScript is event-driven computation 4

Upload: khangminh22

Post on 22-Apr-2023

3 views

Category:

Documents


0 download

TRANSCRIPT

JavaScript Elements

JavaScript• Interpreted programming language with OO capabilities • Core syntax resembles C, C++ and JAVA • However:

– Loosely typed - variables do not need to have a type specified – JS Objects are more like hash tables or associative arrays than

they are like structs (C) or objects (C++, Java) – OO inheritance is prototype-based – Draws inspiration from Perl in regular expressions and array-

handling features

2

3http://www.ecma-international.org/publications/standards/Ecma-262.htm

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)

• We’ll call collections of JavaScript code scripts, not programs

Overview of JavaScript• JavaScript can be used to:

– replace some of what is typically done with applets (except graphics)

– replace some of what is done with CGI - namely server-side programming (but no file operations or networking)

• User interactions through forms are easy • The Document Object Model makes it possible to

support dynamic HTML documents with JavaScript – Much of what we will do with JavaScript is event-driven

computation

4

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

• 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 • All JavaScript objects are accessed through references

5 6

JavaScript and JAVA• JavaScript and Java are only related through syntax • JAVA is strongly typed - types are known at compile time

and operand types (τύποι τελεστέων) are checked for compatibility

• Variables in JavaScript are dynamically typed – Compile-time type checking impossible

• Objects in JAVA are static: – their collection of data members and methods is fixed at

compile time • JavaScript objects are dynamic:

– members of an object can change during execution

Browsers and HTML/JavaScript Documents• What happens when the browser encounters a JavaScript

script in a document? • Two approaches for embedding JavaScript in HTML

documents: – Explicit embedding (ρητή ενσωμάτωση)

<script type = "text/javaScript"> -- JavaScript script – </script> – Implicit embedding (υπόρρητη ενσωμάτωση)

<script type = "text/javaScript" src = "myScript.js"> </script>

7

Implicit vs Explicit JavaScript• Explicit embedding:

– Mixes two types of notation inside the same document (bad for readability)

– Makes maintenance difficult - often different people manage the HTML and the JavaScript

• Depending on its use, a JavaScript script that is explicitly embedded appears in: – The head of an HTML document - for scripts that produce

content only upon request or for those that react to user interactions • These scripts contain function definitions and code associated with form

elements – The body of an HTML document - for scripts that are to be

interpreted just once, as they are found8

JavaScript embedding• Scripts are usually hidden from browsers that

do not include JavaScript interpreters by putting them in special comments: <!-- -- JavaScript script – //-->

• This is also required by the HTML validator • Note that the comment closure is in a new line and is also a JS comment

9

JavaScript objects• Objects are collections of properties:

– data properties (primitive values and references to objects) – method properties (methods)

• Objects are accessed indirectly through variables – The properties of an object are referenced by attaching the

name of a property to the variable that references the object. E.g. myCar.engine

• Objects are dynamic collections of property-value pairs – Properties are names – Values are data values or functions

• All functions are objects and are referenced through variables

10

JavaScript objects• An object can represent:

– Unordered collection of named values – Ordered collection of numbered values: array – An entity that has executable code associated with it:

function • Because these three kinds of objects behave differently,

we treat them as distinct datatypes • There are also specialised objects which represent new

classes of objects: – Date – RegExp – Error

11 12

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>This is a test on Javascript and HTML</title></head><body><h2>The Table of factorials</h2><script><!-- var fact=1; for (i=1;i<10;i++) {

fact = fact*i;document.write(i + "! =" + fact + "<br>");

} //--></script></body></html>

Client-Side JavaScript

13

General Syntactic Characteristics• Identifier: simply a name, used to:

– name variables and functions – provide labels for certain loops – syntax same as Java:

• begin with a letter or underscore, followed by any number of letters, underscores, and digits

• case sensitive

• Comments: both // and /* … */

14

Primitives, Operations, Expressions • 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 (values do have type)

• Variables can be either implicitly or explicitly declared var sum = 0, today = "Monday", flag = false;

Primitives, Operations, Expressions • Numeric operators - ++, --, +, -, *, /, %

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

• The Math Object provides floor, round, max, min, trig functions, etc. e.g., Math.cos(x)

• The Number Object collects useful properties that have constant values – 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 – NaN is not 55 to any number, not even itself – Test for it with isNaN(x)

• Number object has the method, toString15

Primitives, Operations, Expressions • Primitives, Operations, & Expressions (continued)

– String catenation operator : + – Coercions (implicit type 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 – Use the String and Number constructors – Use toString method of numbers – Use parseInt and parseFloat on 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') – substring(from, to) e.g., str.substring(1, 3)– toLowerCase() e.g., str.toLowerCase()

16

Primitives, Operations, Expressions • The typeof operator

– Returns "number", "string", or "boolean" for Number, String, or Boolean, "undefined" for Undefined, "function" for functions, and "object" for objects and for NULL

• Assignment statements – just like C++ and Java • 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 • getHours – returns the hour (0 – 23) • getMinutes – returns the minutes (0 – 59) • getMilliseconds – returns the millisecond (0 – 999)

17

Screen output and keyboard input• JavaScript models the HTML document inside which a script

is embedded, as a 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 (window is self-referential)

– The Document object has a method, write, which dynamically creates content • Its 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)

18

19

Window

Document

Screen output• The Window object has three methods for creating dialog boxes:

– alert, confirm, and prompt • alert("Hej! \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

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

20

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 24

25

// roots.js // Compute the real roots of a given quadratic // equation. If the roots are imaginary, this script // displays NaN, because that is what results from // taking the square root of a negative number

// Get the coefficients of the equation from the user

var 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 result

var root_part = Math.sqrt(b * b - 4.0 * a * c); var denom = 2.0 * a;

// Compute and display the two roots

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

Control Statements• Similar to C, Java, and C++

– Compound statements are delimited by braces, but compound statements are not blocks

• Control expressions – three kinds – 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

– Relational Expressions • The usual six: 55, !5, <, >, <5, >5 • Operands are coerced if necessary

• If one is string and one is number: attempts to convert string to num • If one is Boolean and other is not, the Boolean operand is coerced to a

number (1 or 0) • The unusual two: === and !==; Same as 55 and !5, except that no

coercions are done (operands must be identical) • E.g. ‘3’ 555 3 evaluates to false

• Comparisons of references to objects are not useful (addresses are compared, not values)

26

Control Statements• 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)

27

Control Statements• 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

28

// borders2.js // An example of a switch statement for table border // size selection

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

(ctd’)30

Document.write("<caption> 2008 NFL Divisional", " Winners </caption>"); document.write("<tr>", "<th />", "<th> American Conference </th>", "<th> National Conference </th>", "</tr>", "<tr>", "<th> East </th>", "<td> Miami Dolphins </td>", "<td> New York Giants </td>", "</tr>", "<tr>", "<th> North </th>", "<td> Pittsburgh Steelers </td>", "<td> Minnesota Vikings </td>", "</tr>", "<tr>", "<th> West </th>", "<td> San Diego Chargers </td>", "<td> Arizona Cardinals </td>", "</tr>", "<tr>", "<th> South </th>", "<td> Tennessee Titans </td>", "<td> Carolina Panthers </td>", "</tr>", "</table>");

31

Control Statements• Loop statements

while (control_expression) statement or cmpnd

for (init; control; increment) stmt or cmpnd

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

do

statement or compound

while (control_expression)

32

33

Object creation and Modification• Objects are often created with a new expression, which

must include a call to a constructor • new creates a blank object - one with no properties

– JavaScript objects do not have types – The constructor both creates and initialises object properties.

E.g., the following command creates an object with some inherited method properties, but no data properties:

var my_car = new Object(); – The following command creates a blank object and assigns two

properties to the object: var my_car = {make: “Ford”, model: “Contour”);

Object properties• Created by assigning a value to a property’s name

my_car.make = “Ford”;

my_car.model = “Contour”;

my_car.engine = new Object(); -- Object nesting

my_car.engine.config = “V6”;

my_car.engine.hp = 200;

• Object properties are not variables - they are just names of values, used with object variables to access property values. E.g.: document.write(my_car.engine);

• The number of properties in a JavaScript object is dynamic - at any time during interpretation, properties can be added to or deleted from an object. delete(my_car.model);

34

Accessing object properties• A property can be accessed the same way it is assigned a

value, namely with the object-dot-property notation • Property names can be accessed also as if they were

elements of an array: for (identifier in object)

statement or compound for (var prop in my_car) document.write(“Name: ”, prop, “; Value:”, my_car[prop] + "<br />");

35

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 – var myList = new Array(24, "bread", true); – var myList2 = [24, "bread", true]; – var myList3 = new Array(24);

• The length of an array is the highest subscript to which an element has been assigned, plus 1 – myList[122] = "bitsy"; // length is 123

• Because the length property 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

36

Arrays (continued)• Array methods:

– join – converts all elements of an array to strings and concatenates them into a single string e.g.var listStr = list.join(", ");

– reverse – sort – e.g., names.sort();

• Coerces elements to strings and puts them in alphabetical order – concat – catenates its actual parameters to the end of the array

object e.g., newList = list.concat(47, 26); – slice - returns the selected elements in an array, as a new array

object • listPart = list.slice(2, 5); • listPart2 = list.slice(2);

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

– push, pop, unshift, and shift37 38

Variables• Variables can be implicitly or explicitly declared:

– Variables declared with a var statement are explicitly declared. – Other variables are implicit.

• Scope of a variable (πεδίο εμβέλειας): the range of statements over which the variable is visible.

• When JS is embedded in an HTML document, the scope of a variable is the range of lines of the document over which the variable is visible.

• Implicitly declared variables have global scope, i.e. they are visible in the entire HTML document or JS file. – This is true also for implicit variables defined inside a

function definition. • Variables explicitly declared inside a function have local scope.

Functionsfunction 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: – can be passed as parameters – be assigned to other variables – be the elements of an array – can be properties to other objects, in which case they act as methods

function fun() { document.write(“Hello world<br/>;} ref_fun = fun; // ref_fun refers to the fun object fun(); // a call to fun ref_fun(); /* Another call to fun */

39

Function definitions• JS interpreter has to see a function definition before it sees

a function call. – Function definitions are placed in the head of an HTML

document (either implicitly or explicitly) – Normally (not always) calls to functions appear in the

document body

40

Parameter passing• Parameters are passed by value, like in C, C++ and Java • When a reference variable is passed (pointing to an object), the semantics are

essentially pass-by-reference (we can change the object’s contents inside the function).

• 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; } ... var listx = new Array(1); ... listx[0] = x; by10(listx); x = listx[0];

41

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 />"); } // A test driver for function params

params("Mozart"); params("Mozart", "Beethoven"); params("Mozart", "Beethoven", "Tchaikowsky");

42

43

Functions as parameters• 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);

44

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

// Test driver 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, "<br />"); med = median(my_list_2); document.write("Median of [", my_list_2, "] is: ", med, "<br />");

45

Constructors• Used to create and initialize properties of newly created objects

function plane(newMake, newModel, newYear){ this.make = newMake; this.model = newModel; this.year = newYear; }

myPlane = new plane("Cessna","Centurnian", "1970");

- Can also have method properties 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;

46

Pattern Matching• JavaScript provides two ways to do pattern matching:

– Using RegExp objects – Using methods on String objects

• Both ways use the same type of regular expressions, which are based on PERL

• Patterns sent as parameters to pattern-matching methods are delimited with slashes: /RegExp/

• Simple patterns: two categories of characters in patterns: – normal characters (match themselves) – meta characters (can have special meanings in patterns--do not match

themselves): \ | ( ) [ ] { } ^ $ * + ? . • A meta character is treated as a normal character if it is backslashed

– Period is a special meta character - it matches any character except newline

47

Pattern Matchingsearch(pattern) – Returns the position in the object string of the pattern

(position is relative to zero); returns -1 if it fails var str = "Gluckenheimer"; var 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]

48

Pattern Matching• Abbreviations

49

\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

Pattern Matching• Quantifiers (ποσοτικοποιητές)

– {n} exactly n repetitions – {m,} at least m repetitions – {m, n} at least m but not more than n repetitions – * 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

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

• Pattern modifiers – The i modifier tells the matcher to ignore the case of letters – /oak/i matches "OAK" and "Oak" – The x modifier tells the matcher to ignore whitespace and comments in the pattern

(allows comments in patterns) • Parenthesised Substring Matches: Including parentheses in a regular expression

pattern causes the corresponding sub-match to be remembered. – For example, /a(b)c/ matches the characters 'abc' and remembers 'b'.

50

Pattern Matching Methods of Stringreplace(pattern, string)

• Finds a substring that matches the pattern and replaces it with the string (g modifier can be used) – The matched substrings are made available through the

predefined variables $1, $2, and so on

var str = "Some rabbits are rabid"; str.replace(/rab/g, "tim");

str is now "Some timbits are timid" $1 and $2 are both set to "rab"

51

Pattern Matching Methods of Stringmatch(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 matches of parenthesised parts of the pattern, if any

var str = "My 3 kings beat your 2 aces"; var matches = str.match(/[ab]/g); - matches is set to ["b", "a", "a"]

52

function tst_phone_num(num) {

// Use a simple pattern to check the number of digits and the dash var ok = num.search(/^\d{3}-\d{4}$/);

if (ok == 0) return true; else return false;

} // end of function tst_phone_num

// A script to test tst_phone_num

var tst = tst_phone_num("444-5432"); if (tst) document.write("444-5432 is a valid phone no <br />"); else document.write("Program error <br />");

tst = tst_phone_num("444-r432"); if (tst) document.write("Program error <br />"); else document.write("444-r432 is not a valid phone no <br />");

tst = tst_phone_num("44-1234"); if (tst) document.write("Program error <br />"); else document.write("44-1234 is not a valid phone no <br /");

53 54