• No results found

Javascript-var-Array-Loop.ppt

N/A
N/A
Protected

Academic year: 2020

Share "Javascript-var-Array-Loop.ppt"

Copied!
40
0
0

Loading.... (view fulltext now)

Full text

(1)

JavaScript

(2)

About JavaScript

JavaScript

is not Java,

or even

related to

Java

 The original name for JavaScript was “LiveScript”  The name was changed when Java became popular

 Now that Microsoft no longer likes Java, its name for their

JavaScript dialect is “Active Script”

Statements in JavaScript resemble statements in Java,

because both languages borrowed heavily from the C

language

 JavaScript should be fairly easy for Java programmers to learn

 However, JavaScript is a complete, full-featured, complex language

(3)

Using JavaScript in a browser

JavaScript code is included within <script> tags:

 <script type="text/javascript">

document.write("<h1>Hello World!</h1>") ; </script>

Notes:

 The type attribute is to allow you to use other scripting languages

(but JavaScript is the default)

 This simple code does the same thing as just putting <h1>Hello World!</h1> in the same place in the HTML document

 The semicolon at the end of the JavaScript statement is optional  You need semicolons if you put two or more statements on the same

line

(4)

JavaScript isn’t always available

Some old browsers do not recognize script tags

 These browsers will ignore the script tags but will display the included

JavaScript

 To get old browsers to ignore the whole thing, use:

<script type="text/javascript">

document.write("Hello World!"); //-->

</script>

 The <!-- introduces an HTML comment

 To get JavaScript to ignore the HTML close comment, -->, the // starts a

JavaScript comment, which extends to the end of the line

(5)

Where to put JavaScript

JavaScript can be put in the

<head>

or in the <body>

of an

HTML document

 JavaScript functions should be defined in the <head>

 This ensures that the function is loaded before it is needed

 JavaScript in the <body> will be executed as the page loads

JavaScript can be put in a separate

.js

file

 <script src="myJavaScriptFile.js"></script>

 Put this HTML wherever you would put the actual JavaScript code

 An external .js file lets you use the same JavaScript on multiple HTML

pages

 The external .js file cannot itself contain a <script> tag

(6)

Primitive data types

JavaScript has three “primitive” types: number, string, and

boolean

 Everything else is an object

Numbers are always stored as floating-point values

 Hexadecimal numbers begin with 0x

 Some platforms treat 0123 as octal, others treat it as decimal  Since you can’t be sure, avoid octal altogether!

Strings may be enclosed in single quotes or double quotes

 Strings can contain \n (newline), \" (double quote), etc.

Booleans are either true or false

 0

,

"0"

, empty strings,

undefined

,

null

, and

NaN

are

false

, other

(7)

Variables

Variables are declared with a

var

statement:

var pi = 3.1416, x, y, name = "Dr. Dave" ;

Variables names must begin with a letter or underscore

Variable names are case-sensitive

Variables are

untyped

(they can hold values of any type)

The word var is optional (but it’s good style to use it)

Variables declared within a function are

local

to

that function (accessible only within that function)

local variables must be declared using var

Variables declared outside a function are

global

(8)

Operators, I

Most JavaScript syntax is borrowed from C

Arithmetic operators (all numbers are floating-point):

+ - * / % ++

--

Comparison operators:

< <= == != >= >

Logical operators:

&& || !

(

&&

and ||

are

short-circuit

operators)

Bitwise operators:

& | ^ ~ << >> >>>

Assignment operators:

(9)

Operators, II

String operator:

+

The conditional operator:

condition

?

value_if_true

:

value_if_false

Special equality tests:

==

and

!=

try to convert their operands to the same type

before performing the test

===

and

!==

consider their operands

unequal

if they are of

different types

Additional operators

(10)

Comments

Comments are as in C++ or Java:

Between

//

and the end of the line

Between

/*

and

*/

Java’s javadoc comments,

/** ... */

, are treated just the

(11)

Statements, I

Most JavaScript statements are also borrowed from C

Assignment: greeting = "Hello, " + name;

Compound statement:

{

statement

; ...;

statement

}

If statements:

if (

condition

)

statement

;

if (

condition

)

statement

; else

statement

;

Familiar loop statements:

while (

condition

)

statement

;

do

statement

while (

condition

);

(12)

Statements, II

The switch statement:

switch (expression) { case label :

statement; break; case label : statement; break; ...

default : statement; }

Other familiar statements:

 break;  continue;

(13)

 <html>

<body>

<script type="text/javascript">

<!--var date = prompt(); today = date.getDay(); switch (today) { case 1: alert("It's Monday") break case 2: alert("It's Tuesday") break case 3: alert("It's Wednesday") break

 case 4:

(14)

If -else

 <html>

<body>

<script type="text/javascript"> var n=0

if (n==0) {

alert("n is zerro") }

else {

alert("n is some thing else") }

(15)

Multiple If -else

 <html>

<body>

<script type="text/javascript"> var n=prompt("Enter number between 1 to 4","1")

if (n==1)

{alert("n is one")} else if(n==2)

{alert("n is two")} else if(n==3)

{alert("n is three")} else if(n==4)

{alert("n is four") }

 else if(n>4)

{alert("You entered number greater than 4, please enter 1-4")} else if(n<1)

{alert("You entered number less than 4, please enter 1-4")}

else

{alert("You did not enter a number!")}

(16)

Boolean operators

 <html>

<body>

<script type="text/javascript">

var n=prompt("Enter a number","1") var enter="You entered a # between" if (n>=1 && n<10)

{alert(enter+" 0 and 10")} else if(n>=10 && n<20) {alert(enter+" 9 and 20")} else if(n>=20 && n<30) {alert(enter+" 19 and 30")} else if(n>=30 && n<40) {alert(enter+" 29 and 40")}

 else if(n>=40 && n<=100)

{alert(enter+" 39 and 100")} else if(n<1 || n>100)

{alert("You entered a # less than 1 or greater than 100")}

else

{alert("You did not enter a number!")}

(17)

JavaScript is not Java

JavaScript has some features that

resemble

features in Java:

 JavaScript has Objects and primitive data types  JavaScript has qualified names; for example,

document.write("Hello World");

 JavaScript has Events and event handlers

 Exception handling in JavaScript is almost the same as in Java

JavaScript has some features

unlike

anything in Java:

Variable names are untyped: the type of a variable depends on the

value it is currently holding

 Objects and arrays are defined in quite a different way

(18)

Exception handling, I

Exception handling in JavaScript is

almost

the same as in Java

throw

expression

creates and throws an exception

 The expression is the value of the exception, and can be of any type

(often, it's a literal String)

try {

statements to try

} catch (

e

) {

// Notice: no type declaration for

e

exception handling statements

} finally {

// optional, as usual

code that is always executed

}

(19)

Exception handling, II

try {

statements to try

} catch (

e

if

test1

) {

exception handling for the case that test1 is true

} catch (

e

if

test2

) {

exception handling for when test1 is false and test2 is true

} catch (

e

) {

exception handling for when both test1and test2 are false

} finally {

// optional, as usual

code that is always executed

}

Typically, the test would be something like

(20)

Object literals

You don’t declare the

types

of variables in JavaScript

JavaScript has object

literals,

written with this syntax:

{

name1

:

value1

, ... ,

nameN

:

valueN

}

Example (from Netscape’s documentation):

 car = {myCar: "Saturn", 7: "Mazda",

getCar: CarTypes("Honda"), special: Sales}

 The fields are myCar, getCar, 7 (this is a legal field name) , and

special

 "Saturn" and "Mazda" are Strings  CarTypes is a function call

 Sales is a variable you defined earlier

(21)

Three ways to create an object

You can use an object literal:

 var course = { number: "CIT597", teacher: "Dr. Dave" }

You can use new to create a “blank” object, and add fields to it

later:

 var course = new Object();

course.number = "CIT597"; course.teacher = "Dr. Dave";

You can write and use a constructor:

 function Course(n, t) { // best placed in <head>

this.number = n; // keyword "this" is required, not optional

this.teacher = t; }

(22)

Array literals

You don’t declare the

types

of variables in JavaScript

JavaScript has array

literals,

written with brackets and

commas

Example: color = ["red", "yellow", "green", "blue"];

Arrays are

zero-based:

color[0]

is

"red"

If you put two commas in a row, the array has an

“empty” element in that location

Example:

color = ["red", , , "green", "blue"];

 color has 5 elements

However, a single comma at the end is ignored

(23)

Four ways to create an array

You can use an array literal:

var colors = ["red", "green", "blue"];

You can use new Array()

to create an empty array:

 var colors = new Array();

 You can add elements to the array later:

colors[0] = "red"; colors[2] = "blue"; colors[1]="green";

You can use

new Array(n)

with a single numeric

argument to create an array of that size

 var colors = new Array(3);

You can use

new Array(…)

with

two or more

arguments

to create an array containing those values:

(24)

The length of an array

If

myArray is an array, its length is given by

myArray.length

Array length can be changed by assignment beyond the

current length

Example:

var myArray = new Array(5); myArray[10] = 3;

Arrays are

sparse

, that is, space is only allocated for

elements that have been assigned a value

 Example: myArray[50000] = 3; is perfectly OK  But indices must be between 0 and 232-1

As in C and Java, there are no two-dimensional arrays; but

(25)

Arrays and objects

Arrays

are

objects

car = { myCar: "Saturn", 7: "Mazda" }

car[7]

is the same as

car.7

car.myCar

is the same as

car["myCar"]

If you

know

the name of a property, you can use dot

notation:

car.myCar

If you

don’t know

the name of a property, but you have

(26)

Array functions

If

myArray

is an array,

myArray.sort()

sorts the array alphabetically

myArray.sort(function(a, b) { return a - b; })

sorts

numerically

myArray.reverse()

reverses the array elements

myArray.push(…)

adds any number of new elements to the

end of the array, and increases the array’s length

myArray.pop()

removes and returns the last element of the

array, and decrements the array’s length

myArray.toString() returns a string containing the values of

(27)

The

for…in

statement

You can loop through all the properties of an object with

for (

variable

in

object

)

statement

;

 Example: for (var prop in course) {

document.write(prop + ": " + course[prop]); }

 Possible output: teacher: Dr. Dave number: CIT597

 The properties are accessed in an undefined order

 If you add or delete properties of the object within the loop, it is

undefined whether the loop will visit those properties

 Arrays are objects; applied to an array, for…in will visit the

“properties” 0, 1, 2, …

(28)

Program using array & for loop

<html>

<body>

<script

language="javascript">

{

var cars = new Array()

cars[0]="Camry";

cars[1]="Corolla";

cars[2]="Accord";

cars[3]="Civic";

cars[4]="Maxima";

for(x=0;x<=4; x++)

(29)

Functions

Functions should be defined in the

<head>

of an

HTML page, to ensure that they are loaded first

The syntax for defining a function is:

function

name

(

arg1

,

,

argN

) {

statements

}

The function may contain return

value

; statements

Any variables declared within the function are local to it

The syntax for calling a function is just

name

(

arg1

,

,

argN

)

Simple parameters are passed

by value,

objects are

(30)

Function program

<html>

<head>

<script language="javascript">

function calculate()

{ var X = 5;

var Y = 4;

var Z= X*Y;

var xval="X has the value: ";

var yval=" Y has the value:

";

document.write(""+xval+""+""

+X+""+","+""+yval+""+""+Y+

""+","+" X*Y is equal

(31)

Regular expressions

A regular expression can be written in either of two ways:

 Within slashes, such as re = /ab+c/

 With a constructor, such as re = new RegExp("ab+c")

Regular expressions are almost the same as in Perl or Java (only

a few unusual features are missing)

string.match(

regexp

) searches

string

for an occurrence of

regexp

 It returns null if nothing is found

 If regexp has the g (global search) flag set, match returns an array of

matched substrings

 If g is not set, match returns an array whose 0th element is the matched

text, extra elements are the parenthesized subexpressions, and the index

(32)

Warnings

JavaScript is a big, complex language

We’ve only scratched the surface

It’s easy to get started in JavaScript, but if you need to use it

heavily, plan to invest time in learning it well

Write and test your programs a little bit at a time

JavaScript is not totally platform independent

Expect different browsers to behave differently

Write and test your programs a little bit at a time

Browsers aren’t designed to report errors

Don’t expect to get any helpful error messages

(33)

Example

<html> <head>

<title> JavaScript 1 </title> <script language="JavaScript">

document.write("<h1>This is it. </h1>"); document.write(Date());

</script> </head> <body>

This is the rest of the page. </body>

(34)

Modified example

<html>

<head>

<title> JavaScript 1 </title> <script language="JavaScript">

var rawDate = Date();

var mon = rawDate.substr(4,3);

document.write("The date is"); document.write(rawDate, "<br>")

document.write("The month is ", mon); //-->

</script> </head> <body> <br>

(35)

Using built-in functions, variables

<html> <head> <title> JavaScript 1 </title> <script language="JavaScript">

<!--var rawDate = Date();

var mon = rawDate.substr(4,3); document.write("The month is "); document.write(mon);

//-->

</script> </head> <body>

<br>

This is the rest of the page. </body> </html>

Variable set to what Date() returns.

(36)

<html>

<head><title>Form example </title> <script language="JavaScript">

function verify(f) {

if (f.lname.value == null || f.address.value == null) { alert("Form needs a last name and an address"); return false;

}

if (f.lname.value == "" || f.address.value == "") { alert("Form needs a last name and an address"); return false;

}

(37)

<body>

<h1> Address Information </h1> <br>

<form method=post enctype="text/plain" action="mailto:[email protected]" onSubmit="return verify(this);">

First Name: <input type="text" name="fname"> <br> Last Name: <input type="text" name="lname"> <br>

Street Address: <input type="text" name="address" size=30> <br> Town/City: <input type="text" name="city"> <br>

State: <select name="state" size=1> <br> <option value="NY" selected> Utah <option value="NY" selected> Idaho <option value="NY" selected> New York <option value="NJ"> New Jersey

<option value="CT"> Connecticut <option value="PA"> Pennsylvania </select> <br>

Status: <input type="radio" name="status" value="R"> Returning client <input type="radio" name="status" value="N"> New client

<hr> Thank you <p>

<input type="submit" value="Send information">

(38)

Javscript Events

Events are actions that can be detected by Javascript

Every element on a web page has certain events which

can trigger Javascript functions

Often placed within the HTML tag

<tag attribute1 attribute2 onEventName="javascript code;">

<a href="" onMouseOver="popupFunc();">

The set of all events which may occur and the page

elements on which they can occur is part of the

Document Object Model(DOM) not Javascript

(39)

Common Javascript Events

Event Occurs when... Event Handler

 click User clicks on form element or link onClick

 change User changes value of text, textarea, or select element onChange  focus User gives form element input focus onFocus

 blur User removes input focus from form element onBlur

 mouseover User moves mouse pointer over a link or anchor onMouseOver  mouseout User moves mouse pointer off of link or anchor onMouseOut  select User selects form element's input field onSelect

 submit User submits a form onSubmit

(40)

The Document Object Model

When a document is loaded in the web browser, a number of

objects are created.

 Most commonly used are window and document

Window

 open(), close(), alert(), confirm(), prompt()

Document

 Contains arrays which store all the components of your page

 You can access and call methods on the components using the arrays  An object may also be accessed by its name

 document.myform.address.value = “123 Main”

 document.myform.reset()

 Can also search for element by name or id  document.getElementById(“myelementid”)

References

Related documents

The biggest advantage to having an external Javascript file is that once the file has been loaded, the script will hang around the browser's cache which means if the Javascript

Level 1 and Level 2 outcomes are still important because participants need to react positively to the training program (Level 1 outcome) and they need to learn the material (Level

You would have a function which takes an input array, assign it to a second variable, arrays in Java are actual objects that can be passed around and treated just like other

Creating a variable in JavaScript is called declaring a variable You scrape a JavaScript variable with the var keyword var carName After the declaration the variable has same

Modifiers are created using react create app up each time we compare date in javascript example, you specify properties to group note that nonterminal, values leap seconds in

Javascript Syllabus Introduction JavaScript Output JavaScript Statements JavaScript Syntax JavaScript Variables JavaScript Operators Control Statements Conditional Statements Data

• JavaScript has a concept of objects and classes (like in Java) but no built-in concept of inheritance (unlike in Java). &gt; Every JavaScript object is really an instance of

Government departments that use electronic mail have an obligation to make employees aware that e-mail messages, like paper records, must be retained and destroyed according