User Tools

Site Tools


eg-259:lecture6

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
eg-259:lecture6 [2013/02/06 21:30] – [Learning Outcomes — Objects] eechriseg-259:lecture6 [2013/02/07 21:09] (current) – [Exercises] eechris
Line 380: Line 380:
   * Example:   * Example:
 <code javascript> <code javascript>
-    for (var prop in myAirplane) { +for (var property in myAirplane) { 
-      document.write(myAirplane[prop] + "<br />"); +  console.log(property + "+ myAirplane[property]); 
-    }+}
 </code> </code>
  
    
- 
 ===== Learning Outcomes — Arrays ===== ===== Learning Outcomes — Arrays =====
  
Line 398: Line 397:
   * What is the form of a nested array literal?    * What is the form of a nested array literal? 
  
 +Fiddle with [[http://jsfiddle.net/cpjobling/bJUZ2/4/|arrays]]
 ===== Arrays ===== ===== Arrays =====
  
Line 421: Line 420:
     myList.length = 150;      myList.length = 150; 
 </code> </code>
-  * Example [[/eg-259/examples/lecture6/insert_names.html|insert_names.html]]+  * Example [[http://jsfiddle.net/cpjobling/mKaqy/2/|insert_names.html]]
  
 ---- ----
 <code javascript> <code javascript>
-<!DOCTYPE html> +/*   insert_names.html  
-<!-- insert_names.html +     The script in this document has an array of 
-The script in this document has an array of +     names, name_list, whose values are in  
-names, name_list, whose values are in +     alphabetic order. New names are input through 
-alphabetic order. New names are input through +     prompt. Each new name is inserted into the  
-prompt. Each new name is inserted into the +     name array, after which the new list is  
-name array, after which the new list is +     displayed. 
-displayed. +*/
---> +
-<html lang="en"> +
-  <head> +
-    <meta charset="utf-8" /+
-    <title> Name list </title> +
-  </head> +
-  <body> +
-    <script> +
-      // The original list of names +
-      var name_list = new Array("Al", "Betty", "Kasper", "Michael", "Roberto", "Zimbo"); +
-      var new_name, index, last;+
  
-      // Loop to get a new name and insert it+// The original list of names 
 +var name_list = ["Al", "Betty", "Kasper", "Michael", "Roberto", "Zimbo"];
  
-      while( new_name = prompt("Please type a new name", ""){+// working variables 
 +var new_name, index, last, result, element $('#result');
  
-        // Loop to find the place for the new name+// Loop to get a new name and insert it 
 +while (new_name = prompt("Please type a new name", "")) {
  
-        last = name_list.length - 1;+    // Loop to find the place for the new name 
 +    last = name_list.length - 1;
  
-        while(last >= 0 && name_list[last] > new_name) { +    while (last >= 0 && name_list[last] > new_name) { 
-          name_list[last + 1] = name_list[last]; +        name_list[last + 1] = name_list[last]; 
-          last--; +        last--; 
-        } +    }
- +
-        // Insert the new name into its spot in the array +
- +
-        name_list[last + 1] = new_name; +
- +
-        // Display the new array+
  
-        document.write("<p><b>The new name list is:</b> ", "<br />"); +    // Insert the new name into its spot in the array 
-        for( index = 0; index < name_list.length; index++) { +    name_list[last 1= new_name;
-          document.write(name_list[index], "<br />"); +
-        } +
-        document.write("</p>"); +
-      } //** end of the outer while loop +
-    </script> +
-  </body> +
-</html>+
  
 +    // Display the new array
 +    result = "<p><b>The new name list is:</b><br />";
 +    element.append();
 +    for (index = 0; index < name_list.length; index++) {
 +        result += name_list[index] + "<br />";
 +    }
 +    result += "</p>";
 +    element.append(result);
 +} //** end of the outer while loop
 </code> </code>
- 
  
 ===== Array methods ===== ===== Array methods =====
Line 496: Line 483:
     * Coerce elements to strings, if necessary, and concatenate them together, separated by commas (exactly like join(", "))      * Coerce elements to strings, if necessary, and concatenate them together, separated by commas (exactly like join(", ")) 
   * ''push'', ''pop'', ''unshift'', and ''shift''   * ''push'', ''pop'', ''unshift'', and ''shift''
-  * Example: [[/eg-259/examples/lecture6/nested_arrays.html|nested_arrays.html]]+  * Example: [[http://jsfiddle.net/cpjobling/XT4vg/1/|nested_arrays.html]]
  
 ---- ----
 <code javascript> <code javascript>
-<!DOCTYPE html> +// nested_arrays.html An example to illustrate an 
-<!-- nested_arrays.html +// array of arrays
-An example illustrate an array of arrays +
---> +
-<html lang="en"> +
-  <head> +
-    <meta charset="utf-8" /+
-    <title> Array of arrays </title> +
-  </head> +
-  <body> +
-    <script type = "text/javascript"> +
-      // Create an array object with three arrays as its elements+
  
-      var nested_array [[24, 6], [1, 3, 5], [10, 20, 30]];+var element $('#result')result_text;
  
-      // Display the elements of nested_list +// Create an array object with three arrays as its  
-      for(var row = 0; row <= 2; row++) { +// elements
-        document.write("Row ", row, ":  ");+
  
-        for(var col = 0; col <2; col++) { +var nested_array [ 
-          document.write(nested_array[row][col], " "); +    [2, 4, 6]
-        } +    [1, 3, 5], 
-        document.write("<br />"); +    [10, 20, 30] 
-      } +];
-    </script> +
-  </body> +
-</html>+
  
-</code>+// Display the elements of nested_list 
 +result_text = "<p>"; 
 +for (var row = 0; row <= 2; row++) { 
 +    result_text += "Row " + row + ":  ";
  
 +    for (var col = 0; col <= 2; col++) {
 +        result_text += nested_array[row][col] + " ";
 +    }
 +    result_text += "<br />";
 +}
 +element.append(result_text + "</p>");
 +</code>
  
 ===== Learning Outcomes — Functions ===== ===== Learning Outcomes — Functions =====
Line 561: Line 544:
   * If ''fun'' is the name of a function,   * If ''fun'' is the name of a function,
 <code javascript> <code javascript>
-    ref_fun = fun; +ref_fun = fun; 
-    . . . +// . . . 
-    ref_fun();  /* A call to fun */ +ref_fun();  /* A call to fun */ 
 </code> </code>
- 
  
 ===== Defining Functions ===== ===== Defining Functions =====
Line 579: Line 561:
   * There is no type checking of parameters, nor is the number of parameters checked (excess actual parameters are ignored, excess formal parameters are set to ''undefined'')   * There is no type checking of parameters, nor is the number of parameters checked (excess actual parameters are ignored, excess formal parameters are set to ''undefined'')
   * All parameters are sent through a property array, ''arguments'', which has the ''length'' property   * All parameters are sent through a property array, ''arguments'', which has the ''length'' property
-  * Example: [[/eg-259/examples/lecture6/parameters.html|parameters.html]]+  * Example: [[http://jsfiddle.net/cpjobling/m8JAL/6/|parameters.html]]
  
 ---- ----
 <code javascript> <code javascript>
-<!DOCTYPE html> +// parameters.html The params function and a test  
-<!-- parameters.html +// driver for it. This example illustrates 
-The params function and a test driver for it. +// function parameters
-This example illustrates function parameters +
---> +
-<html lang="en"> +
-  <head> +
-    <meta charset="utf-8" /+
-    <title> Parameters </title> +
-    <script> +
-      // Function params +
-      // Parameters: two named parameters and one unnamed +
-      //             parameter, all numbers +
-      // Returns: nothing+
  
-      function params(a, b) { +var element = $('#result');
-        document.write("Function params was passed ", arguments.length, " parameter(s) <br />"); +
-        document.write("Parameter values are: <br />");+
  
-        for(var arg = 0; arg < arguments.length; arg++) { +// Function describe_params 
-          document.write(arguments[arg], "<br />"); +// Parameters: two named parameters and one unnamed 
-        } +//             parameter, all numbers 
-        document.write("<br />"); +// Returns: nothing
-      } +
-    </script> +
-  </head> +
-  <body> +
-    <script> +
-      // A text driver for params+
  
-      params("Mozart"); +function describe_params(a, b{ 
-      params("Mozart""Beethoven"); +    var text = "Function <em>describe_params</em> was passed + arguments.length + parameter(s) <br />+ 
-      params("Mozart", "Beethoven", "Tchaikowsky");+        "Parameter values are: <br />";
  
-    </script> +    for (var arg = 0; arg arguments.length; arg++) { 
-  </body+        text += arguments[arg] + "<br />"; 
-</html+    } 
-</code>+    text += "In addition named-parameter <em>a</emwas " + a + 
 +            " and <em>b</emwas " + b; 
 +    return text; 
 +}
  
 +// A text driver for params
 +
 +element.append("<p>" + describe_params("Mozart") + "</p>");
 +element.append("<p>" + describe_params("Mozart", "Beethoven") + "</p>");
 +element.append("<p>" + describe_params("Mozart", "Beethoven", "Tchaikowsky") + "</p>");
 +</code>
  
 ===== Passing a Function: Sorting ===== ===== Passing a Function: Sorting =====
Line 650: Line 622:
   * It is given a name by assigning it to a variable -- in this case ''function_name''.   * It is given a name by assigning it to a variable -- in this case ''function_name''.
   * This makes explicit the fact that a function is just another primitive in JavaScript.   * This makes explicit the fact that a function is just another primitive in JavaScript.
-  * You'll see this form used a lot in [[http://codeyear.com|CodeYear]] and in event handlers to come later. +  * You'll see this form used a lot in the [[http://www.codecademy.com/tracks/javascript|Codecademy JavaScript course]] and in the definition of event handlers and call-backs to come later.
  
  
 ===== Another Example ===== ===== Another Example =====
  
-  * [[/eg-259/examples/lecture6/medians.html|medians.html]]+  * [[http://jsfiddle.net/cpjobling/vwYGr/3/|medians.html]]
  
 ---- ----
Line 667: Line 638:
  
 <code javascript>  <code javascript> 
-<!DOCTYPE html> +// medians.js 
-<!-- medians.html +// A function and a function tester 
-A function and a function tester +// Illustrates array operations
-Illustrates array operations +
---> +
-<html lang="en"> +
-  <head> +
-    <meta charset="utf-8" /> +
-    <title> Median Computation </title> +
-    <script> +
-      /* Function median +
-       Parameter: An array of numbers +
-       Result: The median of the array +
-       Return value: none +
-       Alternative function definition +
-       */+
  
-      var median = function (list) { 
-        list.sort(function(a, b) { 
-          return a - b; 
-        }); 
-        var list_len = list.length; 
  
-        // Use the modulus operator to determine whether +var element = $('#result');
-        //  the array's length is odd or even +
-        // Use Math.floor to truncate numbers +
-        // Use Math.round to round numbers+
  
-        if((list_len % 2) == 1) { +/ 
-          return list[Math.floor(list_len 2)]; +     Function median 
-        } +     Parameter: An array of numbers 
-        else { +     Return valueThe median of the array 
-          return Math.round((list[list_len / 2 - 1] + list[list_len / 2]) / 2); +*/
-        } +
-      }; // end of function median note semicolon +
-    </script> +
-  </head> +
-  <body> +
-    <script> +
-      var my_list_1 = [8, 3, 9, 1, 4, 7]; +
-      var my_list_2 = [10, -2, 0, 5, 3, 1, 7]; +
-      var med = median(my_list_1); +
-      document.write("Median of [", my_list_1, "] is", med, "<br />"); +
-      med = median(my_list_2); +
-      document.write("Median of [", my_list_2, "] is: ", med, "<br />"); +
-    </script> +
-  </body> +
-</html> +
-</code>+
  
 +var median = function (list) {
 +    list.sort(function (a, b) {
 +        return a - b;
 +    });
 +    var list_len = list.length;
 +
 +    // Use the modulus operator to determine whether
 +    //  the array's length is odd or even
 +    // Use Math.floor to truncate numbers
 +    // Use Math.round to round numbers
 +
 +    if ((list_len % 2) == 1) {
 +        return list[Math.floor(list_len / 2)];
 +    } else {
 +        return Math.round((list[list_len / 2 - 1] + list[list_len / 2]) / 2);
 +    }
 +}; // end of function median -- note semicolon
 +
 +var my_list_1 = [8, 3, 9, 1, 4, 7],
 +    my_list_2 = [10, -2, 0, 5, 3, 1, 7],
 +    med;
 +
 +med = median(my_list_1);
 +element.append("<p>Median of [" + my_list_1 + "] is: " + med + "</p>");
 +
 +med = median(my_list_2);
 +element.append("<p>Median of [" + my_list_2 + "] is: " + med + "</p>");
 +</code>
  
  
Line 731: Line 693:
     myPlane = new Plane("Cessna", "Centurian", "1970");      myPlane = new Plane("Cessna", "Centurian", "1970"); 
 </code> </code>
 +
 +[[http://jsfiddle.net/cpjobling/s8kFw/6/|Fiddle with constructors]].
  
 ---- ----
  
 Note by convention, constructors use upper case names to distinguish them from ordinary functions. Think //proper noun//. Note by convention, constructors use upper case names to distinguish them from ordinary functions. Think //proper noun//.
- 
  
 ===== Method Properties ===== ===== Method Properties =====
Line 810: Line 773:
 ===== Exercises ===== ===== Exercises =====
  
-Write, test and debug (if necessary) XHTML files that include JavaScript scripts for the following problems. When required to write functions, you must include a script to test the function with at least two different data sets.+Use jsFiddle or some other method to write, test and debug (if necessary) HTML files that include JavaScript scripts for the following problems. When required to write functions, you must include a script to test the function with at least two different data sets.
  
   - //Output//: A table of numbers from 5 to 15 and their squares and cubes, using alert.   - //Output//: A table of numbers from 5 to 15 and their squares and cubes, using alert.
-  - //Output//: The first 20 Fibonacci numbers, which are defined as in the following sequence 1, 1, 2, 3, … where each number in the sequence is the sum of the two previous numbers. Use ''document.write'' to produce the output.+  - //Output//: The first 20 Fibonacci numbers, which are defined as in the following sequence 1, 1, 2, 3, … where each number in the sequence is the sum of the two previous numbers. Use ''console.log'' to produce the output.
   - Modify the script of Exercise 2 to input a number, //n//, using ''prompt'', which is the number of the Fibonacci number required as output.   - Modify the script of Exercise 2 to input a number, //n//, using ''prompt'', which is the number of the Fibonacci number required as output.
   - //Function//: ''no_zeros''; //Parameter//: An array of numbers; //Result//: The array must be modified to remove all zero values. //Returns//: ''true'' if the given array included zeros; ''false'' otherwise.   - //Function//: ''no_zeros''; //Parameter//: An array of numbers; //Result//: The array must be modified to remove all zero values. //Returns//: ''true'' if the given array included zeros; ''false'' otherwise.
eg-259/lecture6.1360186215.txt.gz · Last modified: 2013/02/06 21:30 by eechris