string object methods math object methods date object ... · arrays dom and bom. text and strings...

29
String object methods Math object methods Date object Arrays DOM and BOM

Upload: others

Post on 14-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

String object methods

Math object methods

Date object

Arrays

DOM and BOM

Page 2: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 objectvar myStr2 = "str2"; // Define a string literaldocument.write(myStr1 + " char[0]: " + myStr1.charAt(0) + "<br />");document.write(myStr2 + " length: " + myStr2.length + "<br />");

Index:

Value: strings.html

Page 3: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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>

strings.html

Page 4: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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

• The tables are called codepages, charset or character set

Page 5: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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>

strings.html

Page 6: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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>

strings.html

Page 7: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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";strVariable = strVariable.toLowerCase();strVariable = strVariable.toUpperCase();

Page 8: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 mathoperations than the usualones we have the Mathobject

// number examples3.142345.789.3333333333333333336.02e23 // 6.02 × 10^231.4738223E-32 // 1.4738223 × 10^-32

Page 9: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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.14var num2 = Math.PI.toPrecision(2); // 3.1

</script>

math.html

Page 10: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 methodshttp://www.javascriptkit.com/jsref/math.shtmlhttp://www.miislita.com/searchito/javascript-math-faqs.html

<script>// a random number generator 1 - 10var num = Math.floor(1 + Math.random() * 10);alert("Math.random(): " + num);

</script>

math.html

Page 11: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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]]]]);

// usagevar s = "Today's date is: ";// Create a date object with current date and timevar dt = new Date();// Get the month, day, and year.s += dt.getDate() + "/";s += (dt.getMonth() + 1) + "/";s += dt.getFullYear();alert("Date(): " + s);

</script>

date.html

Page 12: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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

• Examples on previous slide and in date.html

Page 13: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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

• Every JavaScript array has a length property. For non-sparse arrays, this property specifies the number of elements in the array. For sparse arrays, length is larger than the index of all elements

Page 14: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 elementsvar myfriends = new Array(); // Define an Array objectvar primes = [2,3,5,7,11]; // Define an Array literal with numbersvar misc = [1.33,true,"Bob"]; // Define an Array literal with mixed contentvar myArray = new Array(2); // pass optional integer to give length==2// Optional, create an array with n + 1 elements and length n + 1 = 3var my3friends = new Array("John", "Bob", "Sue");

for (i = 0; i < my3friends.length; i++) { alert("my3friends: " + my3friends[i]);}// Create a multidimensional arrayvar table = new Array(10); // 10 rows of the tablefor(var i = 0; i < table.length; i++) table[i] = new Array(10); // Each row has 10 columns

</script>

array.html

strings

Page 15: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 newArrayvar myArray = new Array(4,3,5,65);var newArray = myArray.slice(0, -1);newArray = newArray.concat(myArray);alert("newArray: " + newArray);

array.html

Page 16: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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

array.html

Page 17: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 libraryvar data = [1,2,3,4,5]; // An array to sum//Compute the sum of the array elementsvar sum = 0; // Start at 0data.forEach(function(value) { sum += value; }); // Add each value to sumalert(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]

array.html

Page 18: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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

– http://kangax.github.io/compat-table/es6/

Page 19: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 – For those few areas where a browser does implement something

in a different way one can use feature sensing to test which one is supported by the current browser

Page 20: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

This is an old BOM!

BOM hierarchy

Page 21: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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

document.write(”text”); instead of window.document.write(”text”);

Page 22: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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)– history.go(number) to load the page a specified number

(positive or negative) of entries away from the current page

Page 23: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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– location.reload() - method forces a reload of the current page

Page 24: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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– http://whatsmyuseragent.com/

Page 25: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 resolutionalert("aH,aW: " + window.screen.availHeight + " " + window.screen.availWidth + "\n" +"h,w: " + window.screen.height + " " + window.screen.width);</script>

Page 26: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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 header of the page which (provided that your visitor does not have a privacy option turned on) will contain the last page that your visitor was on before coming to the current page

Page 27: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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])– Opens a new window or document and loads the document specified by

a given URL. Also, opens a new window that uses the sUrl parameter and the sName parameter to collect the output of the write method and the writeln method.

Page 28: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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>

myopen.html

Page 29: String object methods Math object methods Date object ... · Arrays DOM and BOM. Text and Strings • JavaScripts fundamental datatype is the object • Any value in JavaScript that

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>

myopen.html