Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Javascript - Software Engineering for the World Wide Web - Slides | SWE 642, Study notes of Software Engineering

Javascript Material Type: Notes; Professor: Dubey; Class: Software Eng for WWW; Subject: Software Engineering; University: George Mason University; Term: Fall 2011;

Typology: Study notes

2010/2011

Uploaded on 11/08/2011

z0-rush
z0-rush 🇺🇸

1 document

1 / 88

Toggle sidebar

Related documents


Partial preview of the text

Download Javascript - Software Engineering for the World Wide Web - Slides | SWE 642 and more Study notes Software Engineering in PDF only on Docsity! 2008 Pearson Education, Inc. All rights reserved. Software Engineering for the World Wide Web JavaScript Dr. Vinod Dubey SWE 642 – Fall 2011 George Mason University 2008 Pearson Education, Inc. All rights reserved. 2 Acknowledgement This lecture has been adapted from chapters 7, 8, 9, and 10 slides for: Internet & World Wide Web How to Program by P.J. Deitel and H.M. Deitel 2008 Pearson Education, Inc. All rights reserved. 5 Introduction • JavaScript is not Java • JavaScript is a scripting language : – Embedded in HTML – Interpreted as the page is loaded – Can manipulate the HTML page • Is executed on the client (client side) 2008 Pearson Education, Inc. All rights reserved. 6 Introduction • Often, JavaScripts appear in the <head> section of the XHTML document – The browser interprets the contents of the <head> section first • A JavaScript starts with the <script> tag • The <script> tag indicates to the browser that the text that follows is part of a script. – Attribute type specifies the scripting language used in the script—such as text/javascript 2008 Pearson Education, Inc. All rights reserved. 7 Simple Program: Displaying a Line of Text in a Web Page • Browser’s document object represents the XHTML document currently being displayed in the browser – Allows a script programmer to specify XHTML text to be displayed in the XHTML document • Browser contains a complete set of objects – that allow script programmers to access and manipulate every element of an XHTML document 2008 Pearson Education, Inc. All rights reserved. 10 Variables in JavaScript • A variable is a location in the computer’s memory where a value can be stored for use by a program • Keyword var is used to declare the names of variables • All variables have a name, type and value – should be declared with a var statement before they are used in a program 2008 Pearson Education, Inc. All rights reserved. 11 Variables • A variable name can be any valid identifier consisting of letters, digits, underscores ( _ ) and dollar signs ($) – that does not begin with a digit and – is not a reserved JavaScript keyword. • Declarations end with a semicolon (;) – Can be split over several lines, with each variable in the declaration separated by a comma – Several variables may be declared in one declaration or in multiple declarations. 2008 Pearson Education, Inc. All rights reserved. 12 More on Variables • JavaScript does not require variables to have a type before they can be used in a program • JavaScript is referred to as a loosely typed language • A variable in JavaScript can contain a value of any data type – JavaScript automatically converts between values of different types for you 2008 Pearson Education, Inc. All rights reserved. 15 | JavaScript keywords. JavaScript keywords break case catch continue default delete do else false finally for function if in instanceof new null return switch this throw true try typeof var void while with Keywords that are reserved but not used by JavaScript abstract boolean byte char class const debugger double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile 2008 Pearson Education, Inc. All rights reserved. 16 The Assignment Operator (=) • A variable is assigned a value with an assignment statement, using the assignment operator, =. • The = operator is called a binary operator, because it has two operands. 2008 Pearson Education, Inc. All rights reserved. 17 Comments in JavaScript • Comments – A single-line comment begins with the characters // and terminates at the end of the line – Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the JavaScript interpreter – Multiline comments begin with delimiter /* and end with delimiter */ 2008 Pearson Education, Inc. All rights reserved. 20 Single-entry/single-exit sequence, selection and repetition structures 2008 Pearson Education, Inc. All rights reserved. 21 Pseudo-code algorithm that uses counter-controlled repetition to solve the class-average problem. Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average 2008 Pearson Education, Inc. All rights reserved. 22 | Counter-controlled repetition to calculate a class average (Part 1 of 3). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 7.7: average.html --> 6 <!-- Counter-controlled repetition to calculate a class average. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Class Average Program</title> 10 <script type = "text/javascript"> 11 <!-- 12 var total; // sum of grades 13 var gradeCounter; // number of grades entered 14 var grade; // grade typed by user (as a string) 15 var gradeValue; // grade value (converted to integer) 16 var average; // average of all grades 17 18 // Initialization Phase 19 total = 0; // clear total 20 gradeCounter = 1; // prepare to loop 21 22 // Processing Phase 23 while ( gradeCounter <= 10 ) // loop 10 times 24 { 25 26 // prompt for input and read grade from user 27 grade = window.prompt( "Enter integer grade:", "0" ); 28 Stores the sum of grades Sets total to 0 Sets gradeCounter to 1 in preparation for the loop Continues the cycle until gradeCounter is greater than 10 2008 Pearson Education, Inc. All rights reserved. 25 Examination-results problem pseudocode. Initialize passes to zero Initialize failures to zero Initialize student to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” 2008 Pearson Education, Inc. All rights reserved. 26 Fig. 7.11 | Examination- results calculation (Part 1 of 3). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 7.11: analysis.html --> 6 <!-- Examination-results calculation. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Analysis of Examination Results</title> 10 <script type = "text/javascript"> 11 <!-- 12 // initializing variables in declarations 13 var passes = 0; // number of passes 14 var failures = 0; // number of failures 15 var student = 1; // student counter 16 var result; // one exam result 17 18 // process 10 students; counter-controlled loop 19 while ( student <= 10 ) 20 { 21 result = window.prompt( "Enter result (1=pass,2=fail)", "0" ); 22 23 if ( result == "1" ) 24 passes = passes + 1; 25 else 26 failures = failures + 1; 27 28 student = student + 1; 29 } // end while 30 Outer control structure Start nested control structure Increment for while loop End nested control structure 2008 Pearson Education, Inc. All rights reserved. 27 | Examination- results calculation (Part 2 of 3). 31 // termination phase 32 document.writeln( "<h1>Examination Results</h1>" ); 33 document.writeln( 34 "Passed: " + passes + "<br />Failed: " + failures ); 35 36 if ( passes > 8 ) 37 document.writeln( "<br />Raise Tuition" ); 38 // --> 39 </script> 40 </head> 41 <body> 42 <p>Click Refresh (or Reload) to run the script again</p> 43 </body> 44 </html> Additional control structure 2008 Pearson Education, Inc. All rights reserved. 30 Fig. 8.1 | Counter-controlled repetition (Part 2 of 2). 2008 Pearson Education, Inc. All rights reserved. 31 | Counter- controlled repetition with the for statement (Part 1 of 2). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 8.2: ForCounter.html --> 6 <!-- Counter-controlled repetition with the for statement. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Counter-Controlled Repetition</title> 10 <script type = "text/javascript"> 11 <!-- 12 // Initialization, repetition condition and 13 // incrementing are all included in the for 14 // statement header. 15 for ( var counter = 1; counter <= 7; ++counter ) 16 document.writeln( "<p style = \"font-size: " + 17 counter + "ex\">XHTML font size " + counter + 18 "ex</p>" ); 19 // --> 20 </script> 21 </head><body></body> 22 </html> Initial value of the control variable Condition to test whether looping should continue Increment to occur after each iteration of the loop Statement inside the for loop 2008 Pearson Education, Inc. All rights reserved. 32 Fig. 8.2 | Counter-controlled repetition with the for statement (Part 2 of 2). 2008 Pearson Education, Inc. All rights reserved. 35 | Using the switch multiple- selection statement (Part 2 of 4). 33 case "3": 34 startTag = "<ol style = \"list-style-type: upper-roman\">"; 35 endTag = "</ol>"; 36 listType = "<h1>Roman Numbered List</h1>"; 37 break; 38 default: 39 validInput = false; 40 } //end switch 41 42 if ( validInput == true ) 43 { 44 document.writeln( listType + startTag ); 45 46 for ( var i = 1; i <= 3; ++i ) 47 document.writeln( "<li>List item " + i + "</li>" ); 48 49 document.writeln( endTag ); 50 } //end if 51 else 52 document.writeln( "Invalid choice: " + choice ); 53 // --> 54 </script> 55 </head> 56 <body> 57 <p>Click Refresh (or Reload) to run the script again</p> 58 </body> 59 </html> Break out of switch statement Beginning of statements to be executed if choice equals “3” Beginning of statements to be executed if choice is anything other than “1”, “2” or “3” No break is necessary, since we’ve come to the end of the switch anyway Statements Statement 2008 Pearson Education, Inc. All rights reserved. 36 | Using the switch multiple-selection statement (Part 3 of 4). 2008 Pearson Education, Inc. All rights reserved. 37 | Using the switch multiple- selection statement (Part 4 of 4). 2008 Pearson Education, Inc. All rights reserved. 40 Fig. 8.11 | Using the break statement in a for statement (Part 1 of 2). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 8.11: BreakTest.html --> 6 <!-- Using the break statement in a for statement. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title> 10 Using the break Statement in a for Statement 11 </title> 12 <script type = "text/javascript"> 13 <!-- 14 for ( var count = 1; count <= 10; ++count ) 15 { 16 if ( count == 5 ) 17 break; // break loop only if count == 5 18 19 document.writeln( "Count is: " + count + "<br />" ); 20 } //end for 21 22 document.writeln( 23 "Broke out of loop at count = " + count ); 24 // --> 25 </script> 26 </head><body></body> 27 </html> Exits the for loop immediately if count == 5 2008 Pearson Education, Inc. All rights reserved. 41 Fig. 8.11 | Using the break statement in a for statement (Part 2 of 2). 2008 Pearson Education, Inc. All rights reserved. 42 | Using the continue statement in a for statement (Part 1 of 2). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 8.12: ContinueTest.html --> 6 <!-- Using the continue statement in a for statement. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title> 10 Using the continue Statement in a for Statement 11 </title> 12 13 <script type = "text/javascript"> 14 <!-- 15 for ( var count = 1; count <= 10; ++count ) 16 { 17 if ( count == 5 ) 18 continue; // skip remaining loop code only if count == 5 19 20 document.writeln( "Count is: " + count + "<br />" ); 21 } //end for 22 23 document.writeln( "Used continue to skip printing 5" ); 24 // --> 25 </script> 26 27 </head><body></body> 28 </html> If count == 5, skips the rest of the statements in the loop, increments count, and performs the loop- continuation test 2008 Pearson Education, Inc. All rights reserved. 45 OBJECTIVES  To construct programs modularly from small pieces called functions.  To create and call new functions.  How to pass information between functions.  How the visibility of identifiers is limited to specific regions of programs.  Global Object and Global functions 2008 Pearson Education, Inc. All rights reserved. 46 Program Modules in JavaScript • JavaScript programs are written by combining new functions that the programmer writes with “prepackaged” functions and objects available in JavaScript • The term method implies that a function belongs to a particular object • We refer to functions that belong to a particular JavaScript object as methods; all others are referred to as functions. 2008 Pearson Education, Inc. All rights reserved. 47 Program Modules in JavaScript (Cont.) • JavaScript provides several objects that have a rich collection of methods for performing – Common mathematical calculations – String manipulations – Date and time manipulations – Manipulations of collections of data called arrays 2008 Pearson Education, Inc. All rights reserved. 50 Programmer-Defined Functions (Cont.) • Each function should perform a single, well- defined task, and the name of the function should express that task effectively – Promotes software reusability 2008 Pearson Education, Inc. All rights reserved. 51 Function Definitions •return statement – passes information from inside a function back to the point in the program where it was called • A function must be called explicitly for the code in its body to execute • The format of a function definition is function function-name( parameter-list ) { declarations and statements } 2008 Pearson Education, Inc. All rights reserved. 52 Function Definitions (Cont.) • Three ways to return control to the point at which a function was invoked – Reaching the function-ending right brace – Executing the statement return; – Executing the statement “return expression;” to return the value of expression to the caller • When a return statement executes, control returns immediately to the point at which the function was invoked 2008 Pearson Education, Inc. All rights reserved. 55 | Programmer- defined maximum function (Part 1 of 3). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 9.3: maximum.html --> 6 <!-- Programmer-Defined maximum function. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Finding the Maximum of Three Values</title> 10 <script type = "text/javascript"> 11 <!-- 12 var input1 = window.prompt( "Enter first number", "0" ); 13 var input2 = window.prompt( "Enter second number", "0" ); 14 var input3 = window.prompt( "Enter third number", "0" ); 15 16 var value1 = parseFloat( input1 ); 17 var value2 = parseFloat( input2 ); 18 var value3 = parseFloat( input3 ); 19 Creates integer values from user input 2008 Pearson Education, Inc. All rights reserved. 56 | Programmer- defined maximum function (Part 2 of 3). 20 var maxValue = maximum( value1, value2, value3 ); 21 22 document.writeln( "First number: " + value1 + 23 "<br />Second number: " + value2 + 24 "<br />Third number: " + value3 + 25 "<br />Maximum is: " + maxValue ); 26 27 // maximum function definition (called from line 20) 28 function maximum( x, y, z ) 29 { 30 return Math.max( x, Math.max( y, z ) ); 31 } // end function maximum 32 // --> 33 </script> 34 </head> 35 <body> 36 <p>Click Refresh (or Reload) to run the script again</p> 37 </body> 38 </html> Calls function maximum with arguments value1, value2 and value3 Variable maxValue stores the return value of the call to maximum Begin function maximum with local variables x, y and z Calls the Math object’s method max to compare the first variable with the maximum of the other two End function maximum 2008 Pearson Education, Inc. All rights reserved. 57 | Programmer-defined maximum function (Part 3 of 3). 2008 Pearson Education, Inc. All rights reserved. 60 Scope Rules (Cont.) •Scoping Example: onload property of the body element calls an event handler when the <body> of the XHTML document is completely loaded into the browser window 2008 Pearson Education, Inc. All rights reserved. 61 | Scoping example (Part 1 of 3). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 9.8: scoping.html --> 6 <!-- Scoping example. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>A Scoping Example</title> 10 <script type = "text/javascript"> 11 <!-- 12 var x = 1; // global variable 13 14 function start() 15 { 16 var x = 5; // variable local to function start 17 18 document.writeln( "local x in start is " + x ); 19 20 functionA(); // functionA has local x 21 functionB(); // functionB uses global variable x 22 functionA(); // functionA reinitializes local x 23 functionB(); // global variable x retains its value 24 25 document.writeln( 26 "<p>local x in start is " + x + "</p>" ); 27 } // end function start 28 Global variable declaration Local variable in function start 2008 Pearson Education, Inc. All rights reserved. 62 | Scoping example (Part 2 of 3). 29 function functionA() 30 { 31 var x = 25; // initialized each time 32 // functionA is called 33 34 document.writeln( "<p>local x in functionA is " + 35 x + " after entering functionA" ); 36 ++x; 37 document.writeln( "<br />local x in functionA is " + 38 x + " before exiting functionA" + "</p>" ); 39 } // end functionA 40 41 function functionB() 42 { 43 document.writeln( "<p>global variable x is " + x + 44 " on entering functionB" ); 45 x *= 10; 46 document.writeln( "<br />global variable x is " + 47 x + " on exiting functionB" + "</p>" ); 48 } // end functionB 49 // --> 50 </script> 51 </head> 52 <body onload = "start()"></body> 53 </html> Local variable in function functionA, initialized each time functionA is called Calls function start when the body of the document has loaded into the browser window 2008 Pearson Education, Inc. All rights reserved. 65 | JavaScript global functions. Global function Description escape Takes a string argument and returns a string in which all spaces, punctuation, accent characters and any other character that is not in the ASCII character set (see Appendix D, ASCII Character Set) are encoded in a hexadecimal format (see Appendix E, Number Systems) that can be represented on all platforms. eval Takes a string argument representing JavaScript code to execute. The JavaScript interpreter evaluates the code and executes it when the eval function is called. This function allows JavaScript code to be stored as strings and executed dynamically. [Note: It is considered a serious security risk to use eval to process any data entered by a user because a malicious user could exploit this to run dangerous code.] isFinite Takes a numeric argument and returns true if the value of the argument is not NaN, Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY (values that are not numbers or numbers outside the range that JavaScript supports)—otherwise, the function returns false. isNaN Takes a numeric argument and returns true if the value of the argument is not a number; otherwise, it returns false. The function is commonly used with the return value of parseInt or parseFloat to determine whether the result is a proper numeric value. parseFloat Takes a string argument and attempts to convert the beginning of the string into a floating-point value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseFloat( "abc123.45" ) returns NaN, and parseFloat( "123.45abc" ) returns the value 123.45). parseInt Takes a string argument and attempts to convert the beginning of the string into an integer value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseInt( "abc123" ) returns NaN, and parseInt( "123abc" ) returns the integer value 123). This function takes an optional second argument, from 2 to 36, specifying the radix (or base) of the number. Base 2 indicates that the first argument string is in binary format, base 8 indicates that the first argument string is in octal format and base 16 indicates that the first argument string is in hexadecimal format. See Appendix E, Number Systems, for more information on binary, octal and hexadecimal numbers. unescape Takes a string as its argument and returns a string in which all characters previously encoded with escape are decoded. 2008 Pearson Education, Inc. All rights reserved. 66 JavaScript: Arrays 2008 Pearson Education, Inc. All rights reserved. 67 OBJECTIVES  To use arrays to store lists of values.  To declare an array, initialize an array and refer to individual elements of an array.  To pass arrays to functions. 2008 Pearson Education, Inc. All rights reserved. 70 Arrays (Cont.) • The first element in every array is the zeroth element. • The ith element of array c is referred to as c[i-1]. • Array names follow the same conventions as other identifiers • Every array in JavaScript knows its own length, which it stores in its length attribute and can be found with the expression arrayname.length 2008 Pearson Education, Inc. All rights reserved. 71 Declaring and Allocating Arrays • JavaScript arrays are Array objects. • Creating new objects using the new operator is known as creating an instance or instantiating an object • Operator new is known as the dynamic memory allocation operator 2008 Pearson Education, Inc. All rights reserved. 72 Examples Using Arrays • Zero-based counting is usually used to iterate through arrays • JavaScript reallocates an Array when a value is assigned to an element that is outside the bounds of the original Array 2008 Pearson Education, Inc. All rights reserved. 75 Fig. 10.3 | Initializing the elements of an array (Part 3 of 3). 2008 Pearson Education, Inc. All rights reserved. 76 Examples Using Arrays (Cont.) • Arrays can be created using a comma-separated initializer list enclosed in square brackets ([]) – The array’s size is determined by the number of values in the initializer list • The initial values of an array can be specified as arguments in the parentheses following new Array – The size of the array is determined by the number of values in parentheses 2008 Pearson Education, Inc. All rights reserved. 77 | Declaring and initializing arrays (Part 1 of 3). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.4: InitArray2.html --> 6 <!-- Declaring and initializing arrays. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Initializing an Array with a Declaration</title> 10 <style type = "text/css"> 11 table { width: 15em } 12 th { text-align: left } 13 </style> 14 <script type = "text/javascript"> 15 <!-- 16 // Initializer list specifies the number of elements and 17 // a value for each element. 18 var colors = new Array( "cyan", "magenta","yellow", "black" ); 19 var integers1 = [ 2, 4, 6, 8 ]; 20 var integers2 = [ 2, , , 8 ]; 21 22 outputArray( "Array colors contains", colors ); 23 outputArray( "Array integers1 contains", integers1 ); 24 outputArray( "Array integers2 contains", integers2 ); 25 26 // output the heading followed by a two-column table 27 // containing the subscripts and elements of theArray 28 function outputArray( heading, theArray ) 29 { Creates an array with four elements, all of which are defined Creates an array with four elements, all of which are defined in an initializer list Creates an array with four elements, two of which reserve space for values to be specified later 2008 Pearson Education, Inc. All rights reserved. 80 Examples Using Arrays (Cont.) •for…in statement – Enables a script to perform a task for each element in an array – Process is known as iterating over the elements of an array 2008 Pearson Education, Inc. All rights reserved. 81 | Summing elements of an array (Part 1 of 2). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.5: SumArray.html --> 6 <!-- Summing elements of an array. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Sum the Elements of an Array</title> 10 11 <script type = "text/javascript"> 12 <!-- 13 var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; 14 var total1 = 0, total2 = 0; 15 16 // iterates through the elements of the array in order and adds 17 // each element's value to total1 18 for ( var i = 0; i < theArray.length; i++ ) 19 total1 += theArray[ i ]; 20 21 document.writeln( "Total using subscripts: " + total1 ); 22 23 // iterates through the elements of the array using a for... in 24 // statement to add each element's value to total2 25 for ( var element in theArray ) 26 total2 += theArray[ element ]; Sums the values of all the elements in theArray by iterating through the elements in order Sums the values of all the elements in theArray by having JavaScript automatically iterate over its elements 2008 Pearson Education, Inc. All rights reserved. 82 | Summing elements of an array (Part 2 of 2). 27 28 document.writeln( "<br />Total using for...in: " + total2 ); 29 // --> 30 </script> 31 </head><body></body> 32 </html> 2008 Pearson Education, Inc. All rights reserved. 85 Passing Arrays to Functions • Pass an array as an argument to a function – Specify the name of the array (a reference to the array) without brackets • Although entire arrays are passed by reference, individual numeric and boolean array elements are passed by value exactly as simple numeric and boolean variables are passed •join method of an Array – Returns a string that contains all of the elements of an array, separated by the string supplied in the function’s argument 2008 Pearson Education, Inc. All rights reserved. 86 | Passing arrays and individual array elements to functions (Part 1 of 3). 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.8: PassArray.html --> 6 <!-- Passing arrays and individual array elements to functions. --> 7 <html xmlns = "http://www.w3.org/1999/xhtml"> 8 <head> 9 <title>Passing arrays and individual array 10 elements to functions</title> 11 <script type = "text/javascript"> 12 <!-- 13 var a = [ 1, 2, 3, 4, 5 ]; 14 15 document.writeln( "<h2>Effects of passing entire " + 16 "array by reference</h2>" ); 17 outputArray( "Original array: ", a ); 18 19 modifyArray( a ); // array a passed by reference 20 21 outputArray( "Modified array: ", a ); 22 23 document.writeln( "<h2>Effects of passing array " + 24 "element by value</h2>" + 25 "a[3] before modifyElement: " + a[ 3 ] ); 26 27 modifyElement( a[ 3 ] ); // array element a[3] passed by value 28 29 document.writeln( "<br />a[3] after modifyElement: " + a[ 3 ] ); 30 Passes array a to function modifyArray by reference Passes array element a[3] to function modifyElement by value 2008 Pearson Education, Inc. All rights reserved. 87 | Passing arrays and individual array elements to functions (Part 2 of 3). 31 // outputs heading followed by the contents of "theArray" 32 function outputArray( heading, theArray ) 33 { 34 document.writeln( 35 heading + theArray.join( " " ) + "<br />" ); 36 } // end function outputArray 37 38 // function that modifies the elements of an array 39 function modifyArray( theArray ) 40 { 41 for ( var j in theArray ) 42 theArray[ j ] *= 2; 43 } // end function modifyArray 44 45 // function that modifies the value passed 46 function modifyElement( e ) 47 { 48 e *= 2; // scales element e only for the duration of the 49 // function 50 document.writeln( "<br />value in modifyElement: " + e ); 51 } // end function modifyElement 52 // --> 53 </script> 54 </head><body></body> 55 </html> Creates a string containing all the elements in theArray, separated by “ ” Multiplies each element in theArray by 2, which persists after the function has finished Multiplies the array element by 2, but only for the duration of the function
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved