Objects are collections of named pieces of data (properties) and object-specific functions (methods). Besides the predefined objects that form the client-side DOM, JavaScript contains several built-in objects such as Date, Math, and Array.
There are several ways in which you can create custom objects in JavaScript. You can use the new operator, a constructor function, or object literals (as of JavaScript 1.2).
var myO = new Object();
function Student (first, last) {
this.first = first;
this.last = last;
}
var student1 = new Student("John", "Doe");
var sudent2 = new Student ("Monty","Burns");
var student1 = {first: "John", last: "Doe"};
Arrays are similar to objects, but rather than storing named pieces of data (as in object properties), arrays contain numbered pieces of data. You can create new arrays using the new Array() constructor, available in JavaScript versions 1.1 and later.
var myArray = new Array();
var myArray = new Array(4);
var myArray = new Array("San Franciso", "LA", "New York", 15);
Read and write array values using the [ ] operator and the index number of the array element. For example, in the preceding array, the value of myArray[0] is "San Francisco."
myArray[0] = "Chicago";
Every array has a length property that indicates how many elements are contained within the array.
var myArray = new Array('"San Franciso", "LA", "New York", 15);
- join() - converts all elements to strings and concatenates them.
- reverse() - reverses the order of elements in an array.
- sort() - sorts the elements in alphabetical order. To sort numerically, you can pass a comparison function as an argument.
- concat() - creates an array with the original elements followed by the arguments specified.
- slice() - returns a subset of the array; can take either one or two arguments. When two arguments are passed, these represent the start and end points of the subset. A single argument represents only the start point of the subset.
In addition, there are several Array methods that are supported by Netscape but not part of the ECMA standard. These include splice(), push() and pop(). Refer to Netscape's client-side documentation for more information.
Individual elements within an array can themselves contain arrays. When referring to an element within a two-dimensional array, use the [ ] operator twice: myArray[x][y].
myArray = new Array(4);
myArray[0] = new Array("A","B","C","D");
myArray[1] = new Array("a","b","c","d");
myArray[2] = new Array("i","ii","iii","iv");
myArray[3] = new Array("I","II","III","IV");
Math is a built-in object with static mathematical methods and constants. Methods include:
- Math.random() - returns pseudo-random number between 0 and 1.
- Math.ceil() - round a number up to the nearest integer.
- Math.floor() - round a number down to the nearest integer.
- Math.round() - round to the nearest integer.
|