Professional Documents
Culture Documents
Arrays
Objects
Variables
Scripting Introduction
Functions
▪ Encapsulate actions for _later_ invocation
▪ Can be invoked multiple times
▪ Wrapped in curly brackets
▪ Can have return values
▪ Parameters passed on in parenthesis
▪ Can also be a parameter
▪ Integral part of inheritance
▪ No methods, are functions as well (see Object section)
[code]
▪ Factoral function
▪ Mask credit card numbers as function
▪ shift() Returns & removes first element and returns its value
name = names.shift(); // "John"
console.log( names ); // [ "Peter", "Jane" ];
© UAS Technikum Wien [code]
Arrays - Useful methods (2)
▪ length; number of elements
names.length; // 3
▪ User-friendly month
▪ European countries
▪ forEach( function( element, ix ) ) Iterates array and calls function with element and index
names.forEach( function( name, ix ) { // <- anonymous function
console.log( ix + " : " + name );
} );
[code]
© UAS Technikum Wien
11
https://www.w3schools.com/jsref/jsref_obj_array.asp
Anonymous Functions (1)
numbers = [ 1, 2, 3, 4 ];
numbers.forEach( function( number ) {
result = 1; ix = 1;
while( ix <= number ) {
result = result * ix;
ix++;
}
console.log( result );
}
);
▪ Con
– Not reusable
– Not unit testable
– Not accessible at runtime
Exercise
[code]
[code]
cards = {
Ace : 11
, King : 5
, Queen : 4
, Jack : 3
, "The Joker" : 15
}
[code]
stack = {};
deck.forEach( function( card ) {
if( ! stack[ card ] ) {
stack[ card ] = 0;
}
stack[ card ]++;
} );
console.log( stack ); // {"Ace":1,"The Joker":1,"Jack":3}
[code]
[code]
[code]
lsManagers = [ “John Wayne”, “Clint Eastwood” ] list of manager names array (of strings)
[more examples]
© UAS Technikum Wien
30
The “window” object (a first visit)
▪ The “window” object is the top most object in JS
▪ In JS nothing exists outside “window”
▪ “self” is an equivalent of “window”
▪ There is a lot to say about it, but for now we are interested in:
– It is parent to “window” methods like alert, prompt, console
– It is parent to all global variables
– We can omit preceding “window” in front of above two (we did
this until now and will continue to do so).
▪ alert( “Hi” ) == window.alert( “Hi” )
▪ alert( s ) == alert( window.s )
[code]
Exercise
38
39
Excercise
Event management - Improve output 2