Software, Systems, and Solutions

"We do not run your business. We make your business run better."

Skip Repetitive Navigational Links

JavaScript Objects


  • JavaScript is "Object based" in much the same way that VisualBasic is:  JavaScript has predefined Objects and uses standard browser objects. For example: 
    • the Array-object
    • the Date-object
    • the Math-object 
    • the String-object
  • There are several other objects - the attached list refers to objects that should work in both Internet Explorer and Netscape.

Object Variables

  • Objects are described by their class definitions and are instantiated with the new operator. An object variable references the object:
  aStuff = new Array(100); 
  • The variable only refers to the object created by the new operation. Here the object variable "aStuff" refers to the array-object created.

Objects, Properties, Methods, Events

  • Access to an object's properties and methods is by a "." operator. 
  • A property is a single value associated with the object (e.g. value and size for a textbox)
    • To access the Array object property length:
               var len = aStuff.lenght;
  • A method is a function associated with the object.  Methods use () which can contain arguments. 
    • To call the Array object method reverse():
               aStuff.reverse();

Array-Object


  • An array is a consecutive group of related memory locations where elements are stored & retrieved via integer indices.
  • JavaScript uses zero-based arrays (0 is the 1st index).
  • Usually array elements are of the same data type (although this is not required).
  • Arrays in JavaScript are "dynamic" - can grow to accommodate new values assigned to it.
  • Every array has the property length which stores the length of the array.
  • Arrays have 3 methods which can be used to manipulate the items in the array:
    • join (array becomes a string with delimeters separating the array elements),
    • sort (sorts the array using a user defined method), &
    • reverse (reverses the order of array elements)

Arrays: Allocation and Initialization

  • Allocate a 10 element Array
    myArray = new Array(5);
  • Allocate an Empty Array
    myArray = new Array();
  • Allocate and Initialize a 5 element Array
    myArray = new Array(10, 20, 30, 40, 50);
    var myArray = [10, 20, 30,40, 50];
  • Allocate and Initialize a 5 element Array skipping one element
    var myArray = [10, 20, , 40, 50];
    the third element in myArray is "undefined"

Arrays: Initialization

  • Array elements must be initialized individually after declaration
myArray[0] = 32 ;
myArray[1] = 15 ;
myArray[2] = 88 ;
myArray[3] = 12 ;
myArray[4] = 43 ;
  • Programming Note: Remember a 5 element array's first element is [0] and last element is [4]

Array: Variable Subscripts

  • Usually individual array elements are accessed using integer variables instead of "hardcoded" integer values
  • These integer variables can be changed
    • Using a loop (as above)
    • Based on user input
    • Using some random #
  • Here's an example of an array that stores strings  and uses a random number to select an individual array element (quote.html).
<head><script language="JavaScript">
function quote()
{
   q = new Array(); //array w/o size
        // Each element added increases array size
   q[0] = 'Form Ever Follows Function';
   q[1] = 'E pluribus unum';
   q[2] = 'When you call me that smile';
   q[3] = 'Let\'s look at the record';
   q[4] = 'WYSIWYG';
                          // Random # between 0 and the array length
   var v=Math.floor(Math.random()*q.length);
   window.status = q[v];
}
</script></head> // Quote changes using 3 events
<body onload = "quote()" onfocus = "quote()" 
      onblur="window.status=''"></body>

Arrays and Functions


Call-by-value

  • In JavaScript when an individual argument is passed to a function it is passed using "Call-by-value"
  • In call-by-value, the called function is passed a variable's value and copies it to the automatic variables in its argument list.
  • Advantage: The called function cannot change the values of the corresponding variables in the calling function.
  • Disadvantage: If a large object is passed, copying it can take extra memory and execution time.

Call-by-reference

  • Arrays (and other Objects) in JavaScript use "Call-by-reference" when passed to a function.
  • Call-by-Reference does not make copies of original data. This allows functions to access and manipulate common data resources.
  • Call-by-value: transmits a copy of a value
  • Call-by-reference: transmits an address


Passing Arrays to Functions

  • To pass an array element as an argument to a function, specify the individual element (passed call-by-value).
       someFunction(response[4]);
  • To pass an entire array as an argument to a function, specify the name of the array without any brackets (passed call-by-reference)
       someFunction(response);
  • To receive an array, the function parameter list must specify that a argument will be received and then that argument must be used as an array within the function
       function someFunction(r)
       { document.write(r.length);}

Using Arrays with Functions

<script language="JavaScript">
var a = [0,99,94,85,87,78,34,90,23,78]; 
var avg = 0;

average(a, avg); //passing an array & a variable

// write out a[0] and avg
// as returned from function averag
e
document.write('<h3>avg. of a[1] through a['); 
document.writeln(a.length-1  + '] is ' + a[0]);
document.writeln(' not ' + avg + '</h3>');

function average(grade, average)
{
  // loop to sum all the items in the array
  // from a[1] through a[a.length-1]
  for (var i=1; i < grade.length; i++)
  {   grade[0] += grade[i];
      average += grade[i];
  }
  grade[0]/=(grade.length-1);result in grades[0]
  average = average/(grade/(length-1))
  // grade[0] and average are identical
}
</script>

 

Date-Object


  • The Date-object lets you work with time and date. Dates include year, month, day, hours, minutes and seconds specified like this:
    Date(year, month, day, hours, mins, secs);
  • To create a new Date object (variable) you use the new command. (Dates use 0 for January - not 1)
    startDay = new Date(2001,0,23,17,35,54);
    // Date: January 23, 2001 at 17:35 & 54 sec. 
  • If you do not specify a date & time when creating a new Date-object the actual date and time is used: 
    today = new Date();

Date Object Methods

  • The Date-object offers methods which can be used to change the values or display the values of a specific instance of the date object (e.g. today). 
    • getHours(), setHours(), getMinutes(), setMinutes(), getMonth(), setMonth() etc. 
  • A Date-object only represents a certain date and time. It is not like a clock which changes the time automatically.
  • Below is a script that outputs the actual date and time:



<script language="JavaScript">
<!-- hide
function myclock(f)
{
  now= new Date();
  var min = now.getMinutes();
  if (min < 10) 
    min = "0" + min;
  f.txtTime.value = "Time: " + now.getHours()
    + ":" + min;
  f.txtDate.value = "Date: "+ (now.getMonth()+1) 
    + "/"+now.getDate() + "/"+now.getYear();
} // -->
</script>
  • Here we use methods like getHours() in order to display the time and date specified in out Date-object now. You can see that we are adding 1 to the month. The method getMonth() returns the number 0 for January so we need to add 1 to get the correct month. 
  • This script checks whether the number of minutes is less than 10. This is so you don't get a time which looks like this: 14:3 when you want 14:03. 
  • To make this into a working clock we would add a timer to the function:
      Timer= setTimeout("myclock()",1000);  
    the setTimeout() method to call the myclock() function every 1000 milliseconds. 
  • See clock.html for a working clock

Math-Object


  • The Math object's methods allow the programmer to perform many common mathematical calculations. 
  • Instead of declaring a Math object.  You access  the Math object's properties & methods using:
    • Math followed by a dot operator (.), 
    • then name of the property or method. 
    • In parentheses following the method name is the argument (or a comma-separated list of arguments). 
  • For example, to calculate the square root of 900.0:
    document.write('<p>sqrt'+Math.sqrt(900.0)');

Math-object Methods

  • Some methods of the Math-object are:
    • Math.ceil(x): rounds to smallest int not < x
    • Math.floor(x): rounds to largest int not > x
    • Math.max(x,y): larger of x and y
    • Math.min(x, y): smaller of x and y
    • Math.pow(x,y): xy
    • Math.round(x): rounds x to the closest integer
    • Math.sqrt(x): square root of x
    • Math.random(): a random number between 0 and 1.
      • document.write(Math.random()):

Math-object Properties

  • The Math-object also has a number of properties/constants that can be used in mathematical calculations: These are (for example):
    • Math.PI: Pi ratio of circle's circumference / diameter (Approx. 3.141592653589793)
    • Math.SQRT1_2: Square root of 0.5 (Approx. 0.707)
    • Math.SQRT2: Square root of 2.0 (Approx. 1.414)

Strings and String-objects


  • A string is a series of characters treated as a single unit. 
    • They may include letters, digits and various special characters, such as +, -, *, /, $ . . . 
    • They are written as a sequence of characters in either double or single quotation marks: 

"John Q. Doe"  
'9999 Main Street'
"Waltham, Massachusetts"
'(201) 555-1212' 

  • A String may be assigned to a variable in a declaration. The declaration
       var color = "blue";
       color = String("blue");

    Either statement initializes variable color as a String object containing the string "blue".
  • Strings can be compared with the relational operators (<, <=, > & >=) and the equality operators (== & !=).

String-object Methods

  • Some String-object methods are:
    • indexOf(substring, index) Searches for the first occurrence of substring starting from position index. 
      • Returns starting index of substring (-1 if not found). 
    • split(delimeter) Splits the string into an array of strings splitting at every delimiter: 
      (e.g. sArray = string1.split(" ");)
    • substr(start, len) Returns a string containing len characters starting from index start in the string.
    • toLowerCase() Returns a lowercase string. 
    • toUpperCase() Returns an uppercase string.
  • Some methods that generate HTML tags:
    • bold() Wraps string in <B></B> tags.
    • fontcolor( color ) Wraps string in <FONT></FONT> tags with color as the font color.
    • link( url ) Wraps string in an anchor element (<A></A>) with url as the hyperlink location.
    • sub() Wraps string in <SUB></SUB> tags.
    • sup() Wraps string in <SUP></SUP> tags.

A String-object Example

  • length: As with arrays strings have a length property that is the number of characters in the string. For example, 
         var my_car = "Ferrari"; 
         var how_long = my_car.length;
     
    • In this case, the variable how_long will have a value of 7, since the word "Ferrari" has seven characters. 

Another String-object Example

  • indexOf is used to check for if character or small string is found within the current string: 
    • It takes an argument, which is the string we are looking for within the current string. 
    • It returns a -1 if the string you searched for is not found, a 0 if it starts at the 1st character etc. 
    • It only returns only the first appearance of your character or string. 
<script language="JavaScript">
<!-- hide
function get_url()
{
  var url = prompt('Enter URL','http://');
  var http_ok = url.indexOf('http://');
  var dot_ok = url.indexOf('.');

  if ((http_ok != 0) {
    alert('Error: URL needs http://!');
    get_url();
  }
  else if (dot_ok == -1) {
    alert('Error: URL needs 1 dot (.)!');
    get_url();
  }
  else
    alert('Thanks!');
}//-->
</SCRIPT>
<FORM>
Submit your URL here: 
<input type = "button" value = "Submit URL" onclick=get_url()>
</FORM>
 
  • This checks to be sure the viewer entered the http:// part of the address. If not, it shows the error alert and gives the viewer a chance to enter the url again.
  • It also ensures there is at least one dot (.) in the address as well. This way, the user would need to have a string plus a dot ( like http://www.west.asu.edu ).