• No results found

IA 08 internet apps js objects pdf

N/A
N/A
Protected

Academic year: 2020

Share "IA 08 internet apps js objects pdf"

Copied!
29
0
0

Loading.... (view fulltext now)

Full text

(1)

String object methods

Math object methods

Date object

Arrays

(2)

Text and Strings

• JavaScripts fundamental datatype is the object

• Any value in JavaScript that is not a

string

, a

number

,

true

,

false

,

null

, or

undefined

is an object!

• A string is a sequence of 16-bit values, each of which

typically represents a Unicode character (UTF-16)

• Declaring strings works as in C# and Java etc.

– The string have character index and lenght

var myStr1 = new String('str1'); // Define a string object

var myStr2 = "str2"; // Define a string literal

document.write(myStr1 + " char[0]: " + myStr1.charAt(0) + "<br />"); document.write(myStr2 + " length: " + myStr2.length + "<br />");

Index:

(3)

The String object

• String literals are not objects but they have properties and

methods anyway

– Everytime you use a string JavaScript convert the string into a temporary String object - as you would do: new String (s);

– The same applies to Number and Boolean

You can break a string across multiple lines by ending

each line but the last with a backslash (\)

– (\) is also used as escape character - for example new line (\n)

When combining Java-Script and HTML, it is a good idea to use

one style of quotes for JavaScript and the other style for HTML

– Using the wrong method below will either give an error or no action at all

<!-- correct -->

<button ondblclick="myFunc('button');">No</button>

<!-- wrong -->

<button ondblclick="myFunc("button");">No</button>

(4)

String methods - charAt(), charCodeAt()

• charAt(index : Number) : String

Returns the character at the specified index of a String

object

• charCodeAt(index : Number) : String

Returns an integer representing the Unicode encoding of

the character at the specified location in a String object

A – Z have decimal Latin-1 values: 65 – 90

a – z have decimal Latin-1 values: 97 – 122

0 – 9 have decimal Latin-1 values: 48 – 57

• For a complete table check with internet and the

ASCII, ISO LATIN-1 (8859-1) or UTF-8 tables

(5)

String methods - indexOf(), lastIndexOf()

• indexOf(subString : String [, startIndex : Number]) : Number

– Returns the character position where the first occurrence of a

substring occurs within a String object

• lastIndexOf(substring : String [, startindex : Number ]) : Number

– Returns the index of the last occurrence of a substring within a

String object

• Optional second parameter is an index to begin the search

• No match gives -1

as return value

• Examples

<script>

function indexDemo(str2){

var str1 = "BABEBIBOBUBABEBIBOBU"; var n = str1.indexOf(str2, 5);

return(n); }

function lastIndexDemo(str2){

var str1 = "BABEBIBOBUBABEBIBOBU"; var n = str1.lastIndexOf(str2); return(n);

}

</script>

(6)

String methods – substr(), substring()

• substr(start : Number [, length : Number]) : String

– Returns a substring beginning at a specified location and having a specified length

– Required first parameter is the starting position of the desired substring. The index of the first character in the string is zero.

– Optional second parameter is the number of characters to include in the returned substring

• substring(start : Number, end : Number) : String

• Example

<script>

function substrDemo(start, len){

var s, ss; // Declare variables.

var s = "The rain in Spain falls mainly in the plain.";

ss = s.substr(start, len); // Get substring.

return(ss); // Returns "Spain". }

<script> <body>

<button onclick="alert(substrDemo('12','5'))">substrDemo(12,5)</button>

<button onclick="alert(substringDemo('12','17'))">substringDemo(12,17)</button> </body>

(7)

String methods – toLowerCase(),

toUpperCase()

• toLowerCase() : String

– Returns a string where all alphabetic characters have been converted to lowercase.

• toUpperCase() : String

– Returns a string where all alphabetic characters have been converted to uppercase

• Example

• There are many more String object methods

to examine

http://www.javascriptkit.com/jsref/string.shtml

var strVariable = "This is a STRING literal";

(8)

Numbers and Arithmetic

• Unlike many languages, JavaScript does not make a

distinction between integer values and floating-point

values

• All numbers in JavaScript are represented as 64 bit

floating-point values

• They can be entered according this syntax

[digits][.digits][(E|e)[(+|-)]digits]

• Arithmetic in JavaScript does not raise errors in cases of

overflow, underflow, or division by zero

– The result in these cases are a special infinity value, which JavaScript prints as Infinity

• For more complex math

operations than the usual

ones we have the Math

object

// number examples

3.14

2345.789

.333333333333333333

6.02e23 // 6.02 × 10^23

(9)

Math methods – toFixed(), toPrecision()

• toFixed( [fractionDigits : Number] ) : String

– Returns a string representation of a number in fixed-point notation

– fractionDigits must be in the range 0 – 20

– If fractionDigits is not supplied or undefined, the toFixed method assumes the value is zero.

toPrecision ( [precision : Number] ) : String

– Number of significant digits. Must be in the range 1 – 21

– For numbers in exponential notation, precision - 1 digits are returned after the decimal point

– For numbers in fixed notation, precision significant digits are returned

– If precision is not supplied or is undefined, the toString method is called instead

<script>

var num1 = Math.PI.toFixed(2); // 3.14

var num2 = Math.PI.toPrecision(2); // 3.1

</script>

(10)

Math methods – random(), floor()

• random() : Number

– Returns a pseudorandom number >= 0.0 and < 1.0

– The pseudorandom number generated is from 0 (inclusive) to 1 (exclusive), that is, the returned number can be zero, but it will always be less than one. The random number generator is seeded automatically when JavaScript is first loaded

floor(number : Number) : Number

– Returns the greatest integer less than or equal to its numeric argument

For more Math object methods

http://www.javascriptkit.com/jsref/math.shtml

http://www.miislita.com/searchito/javascript-math-faqs.html

<script>

// a random number generator 1 - 10

var num = Math.floor(1 + Math.random() * 10); alert("Math.random(): " + num);

</script>

(11)

The Date object

• Enables basic storage and retrieval of dates and times

– The dateVal argument

• If a numeric value, dateVal represents the number of milliseconds in UCT (Universal Coordinated Time) between the specified date and midnight January 1, 1970

• If a string, dateVal is parsed according to the rules in Formatting Date and Time Strings

See the documentation for the other arguments

<script>

// var dateObj = new Date(); // different Date constructors

// dateObj = new Date(dateVal);

// dateObj = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]);

// usage

var s = "Today's date is: ";

// Create a date object with current date and time

var dt = new Date();

// Get the month, day, and year.

s += dt.getDate() + "/";

s += (dt.getMonth() + 1) + "/"; s += dt.getFullYear();

alert("Date(): " + s); </script>

(12)

Date methods - getDate(), getDay(),

getMonth(), getFullYear()

• Date objects are not a fundamental type like numbers are

• getFullYear() : Number

– Returns the year value in the Date object using local time

• getDate() : Number

– Returns the day of the month value in a Date object using local time, numbers between 1 - 31

• getMonth() : Number

– Returns the month value in the Date object using local time, numbers between 0 - 11 where 0 is january

• getDay() : Number

– Returns the day of the week value in a Date object using local time, numbers between 0 - 6 where 0 is sunday

(13)

Array rules

• An array is an ordered collection of values where each value is called an element, and each element has a numeric position in the array - the index

• JavaScript arrays are untyped: an array element may be of any type, and different elements of the same array may be of different types

• Array elements may even be objects or other arrays, which allows you to create complex data structures, such as arrays of objects and

arrays of arrays

• JavaScript arrays are zero-based and use 32-bit indexes: the index of the first element is 0, and the highest possible index is 2^32 - 2

• JavaScript arrays are dynamic: they grow or shrink as needed and there is no need to declare a fixed size for the array when you create it or to reallocate it when the size changes

• JavaScript arrays may be sparse: which means the elements need not have contiguous indexes and there may be gaps

(14)

Arrays

• Provides support for creation of arrays of any data type

– length is a read/write property. You may set this property to dynamically expand an arrays length

<script>

var empty = []; // Define an empty Array literal with no elements

var myfriends = new Array(); // Define an Array object

var primes = [2,3,5,7,11]; // Define an Array literal with numbers

var misc = [1.33,true,"Bob"]; // Define an Array literal with mixed content var myArray = new Array(2); // pass optional integer to give length==2 // Optional, create an array with n + 1 elements and length n + 1 = 3 var my3friends = new Array("John", "Bob", "Sue");

for (i = 0; i < my3friends.length; i++) { alert("my3friends: " + my3friends[i]); }

// Create a multidimensional array

var table = new Array(10); // 10 rows of the table

for(var i = 0; i < table.length; i++)

table[i] = new Array(10); // Each row has 10 columns

</script>

array.html

(15)

Array methods – concat(), slice()

• concat([item1 : { Object | Array } [, ... [, itemN : { Object |

Array }]]]]) : Array

– Returns a new array consisting of a combination of the current array and any additional items

– Optional. Additional items to add to the end of the current array

• slice(start : Number [, end : Number]) : Array

– Returns a section of an array

– Required. The index to the beginning of the specified portion of the array

– Optional. The index to the end of the specified portion of the array

• Example

// In the following example, all but the last element // of myArray is copied into newArray

var myArray = new Array(4,3,5,65);

var newArray = myArray.slice(0, -1); newArray = newArray.concat(myArray); alert("newArray: " + newArray);

(16)

Array methods – join(), sort(), reverse()

• join(separator : String) : String

– Returns a string value consisting of all the elements of an array concatenated together and separated by the

specified separator character.

– Required. A string that is used to separate one element of an array from the next in the resulting String object. If

omitted, the array elements are separated with a comma.

• sort(sortFunction : Function ) : Array

– Returns an Array object with the elements sorted

reverse() : Array

– Returns an Array object with the elements reversed

• Example

var a = new Array(1,0,4,3,2);

alert("isArray: " + Array.isArray(a));

var b = a.join("-"); a = a.sort();

a = a.reverse();

alert("join.sort-reversed: " + b + ":" + a);

(17)

ECMAScript 5 Array methods

• ECMAScript 5 defines 9 new array methods for iterating, mapping, filtering, testing, reducing, and searching arrays

• In most cases, the function you supply is invoked with three

arguments: the value of the array element, the index of the array element, and the array itself. Often, you only need the first of these argument values

• forEach(), map(), filter(), every() and some(), reduce(), reduceRight(), indexOf() and lastIndexOf()

• CodeLobster does not support ECMAScript 5, to know what is supported you need feature detection as in the Modernizr library

var data = [1,2,3,4,5]; // An array to sum

//Compute the sum of the array elements

var sum = 0; // Start at 0

data.forEach(function(value) { sum += value; }); // Add each value to sum

alert(sum); // => 15

var a = [1, 2, 3];

var b = a.map(function(x) { return x*x; }); // b is [1, 4, 9]

a = [5, 4, 3, 2, 1];

var smallvalues = a.filter(function(x) { return x < 3 }); // [2, 1]

var everyother = a.filter(function(x,i) { return i%2==0 }); // [5, 3, 1]

(18)

ECMAScript 6 (2015), 7 (2016), ...

• ECMAScript constantly add new functons and syntax

– https://en.wikipedia.org/wiki/ECMAScript#Versions • Browser compability pages can be benefitial to examine

(19)

HTML DOM and BOM

• DOM (Document Object Model)

– The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically

access and update the content, structure and style of documents

– The document can be further processed and the results of that processing can be incorporated back into the presented page

– DOM is a subset of BOM and standardized by W3C: http://www.w3.org/DOM/

• BOM (Browser Object Model)

– The BOM is that part of JavaScript that allows JavaScript to interface and interact with the browser itself

– There is no official standard for BOM

– Fortunately most browsers have implemented the same commands to do the same (or almost the same) things

(20)

This is

an old

(21)

The window object

• The most commonly used object within the BOM

• Almost everything that you have in the browser is a

property or method of that object

– The DOM for the web page is attached as window.document

• Since it is the highest object in the DOM hierarchy it is not

neccessary to include window before document when

accessing methods and properties

– We write alert(”text”); instead of window.alert(”text”); or

(22)

The history object

• The window.history object within the BOM contains the

history of the web pages that the browser has visited

• To protect the privacy of the person using the browser

there is only limited ways in which JavaScript can interact

with this object

– The only property of the history list that JavaScript has read access to is history.length

• There are 3 methods for moving to a different page in the

list

history.back() to load the immediately preceding page from the list (if there is one)

history.forward() to load the immediately following page from the list (if there is one)

(23)

The location object

• The window.location object have the possibility to access the

current page URL and change it to another page as well as all

the different parts of the URL via properties

• There are 8 properties and 3 methods

location.href - which is the exact equivalent

of window.document.url

location.protocol - check if http:// or https://

location.port - test if port 80 or 443

location.hash - is anchor reference if there is one

location.search - returns the query string from the URL

location.host - field contains the domain name and port number

location.hostname - allows us to access the domain name without any of the rest of the address information

location.assign(url) - method loads a new HTML document

location.replace(url) - method pass a new URL into the location writing a new entry into history

(24)

The navigator object

• The window.navigator object contains browser and

OS-information

• The most common usage is to find out

navigator.browserLanguage

navigator.systemLanguage

navigator.userAgent is a property all browsers implement

navigator.appCodeName

navigator.appName, and

navigator.appVersion

are all extracted from navigator.userAgent

• Example navigator.userAgent string

– Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2

(25)

The screen object

• The window.screen object contains information about the

visitors display properties

• There are only two of theese that are useful

with regard to JavaScript

screen.availWidth and screen.availHeight which give the width and height of the available area of the screen (after subtracting any fixed toolbars) into which you can open, move, or resize a browser window

– Note that nothing with regard to the screen is of any use when it comes to the JavaScript that is interacting with the browser window itself since the browser may or

may not be maximised within the available area of the screen

– Making the web page layout dependent on the screen size is a common error that newcomers make that results in their page

displaying unwanted scrollbars almost all the time -

since the browser viewport size is almost always smaller than the screen size

<script> // Windows taskbar steals about 30px in this screen resolution

alert("aH,aW: " + window.screen.availHeight + " " + window.screen.availWidth + "\n" +"h,w: " + window.screen.height + " " + window.screen.width);

(26)

The document object

• This object contains DOM properties and methods,

some are aliased from window/BOM

• There are 3 of these properties which most browsers

support and which may have some use

document.URL contains the address of the current page and is a place where you can read the path and filename of the current page from. By updating

the field you can also redirect the browser to the specified URL

document.lastModified provided that the

date/time is actually passed from the server will display when the page was last modified

document.referrer reads the referrer

(27)

DOM – collections and methods

• document.images

– This object is an Array of images

– Every image on a web page is saved in the images Array

– Accessing the document.images[index] or properties/methods opens up a lot of functionality

• document.getElement*

– When using document.getelementById(sIDValue) you get a variable to use with for example the property innerHTML

• You can get or set the HTML code between the start and end tag of the object (see earlier example in the slides)

– Many more methods and properties exist for manipulating elements in the DOM, for example: append*, remove*, replace*

• object.open(sUrl [, sName] [, sFeatures] [, bReplace])

(28)

object.open() cont.

• sUrl - required

– Is either the MIME type for a new document or an URL when a new window is opened

• sName - optional

– When a new document is opened it specify the string replace in the history list. When a new window is opened this is a string that specifies the name of the window

• sFeatures - optional

– This String parameter is a list of comma-separated items. Each item consists of an option and a value, separated by an equals sign (=), for example, "fullscreen=yes, toolbar=yes". Many features are supported!

• bReplace - optional

– When the sUrl is loaded into the same window, this boolean

parameter specifies whether the sUrl creates a new entry or

replaces the current entry in the window's history list.

<head> <script>

function myOpen() {

open('about:blank'); }

</script> </head>

<body onclick="myOpen();">

Click this page and window.open() is called. <button onclick="open('about:blank');">

Click this button and document.open() is called. </button>

</body>

(29)

document.open()

• The following example shows how to use the open method to

replace the current document with a new document and display

the HTML markup contained in the variable sMarkup

<!doctype html> <html>

<head>

<title>My Open</title> <script>

function replace(){

var oNewDoc = document.open("text/html", "replace");

var sMarkup = "<html><head><title>New Document</title>"

+ "</head><body>Hello, world replace!</body></html>"; oNewDoc.write(sMarkup);

// we can either close the window or the document with object.close();

}

</script> </head> <body>

<!-- Button calls the replace function which replace the current page with a new one -->

<input type="button" value="document.open" onclick="replace();"> </body>

</html>

References

Related documents

Arrays and c declare array with an individual array is allowed will then the same type when referencing and use it with the values, else knows how!. Document may be inconvenient, it

An desktop is a variable containing multiple values Any variable may be used as an array There mediate no maximum limit skip the size of now array than any requirement that

An array is a collection of more than one homogenous element. The data items /elements of the same type and same length are the homogenous elements. To represent

Minimum Length (of element in array): 2 Maximum Length (of element in array): 15 Minimum Items (of elements in array): 0 Maximum Items (of elements in array): 4.

If a fault condition occurs, to find out the exact number of characters in a string, if type of elements in array is structure objects then type of array becomes the structure..

An Object is an array of elements of the same type (int, float, structures, strings,...), and different Objects may have dif- ferent types. The User can dynamically create or

– Initialize elements of 10-element array to even integers... All

To construct an array with a given number of elements... Syntax 8.2: Array