HTML and CSS Reference
In-Depth Information
fruit [ 3 ]= ”plums” ;
document . write ( fruit [ 1 ]);
var myFruit = fruit . pop ();
document . write ( “<br>” + myFruit + “<br>” );
document . write ( fruit . length );
</script>
< meta http - equiv = ”Content-Type” content = ”text/html; charset=UTF-8” >
< title > Array 1 </ title >
</ head >
</ html >
h e result of the preceding program are the words peaches, plums, and 3 on the screen.
Peaches was pulled out of the array by number reference and placed into a screen output
function. h en using the pop() method, the element on the top of the array was placed into
a variable named myFruit and displayed to the screen. Finally, the pop() method removed
one element from the array and placed it into the myFruit variable, so now the array has a
length of 3 — and that's what's shown on the screen. Each element in an array works just like a
variable. h e dif erence is that it's part of a larger object — the array.
OBJECTS
h e i nal data type used to store values is an object. (Wasn't the Array an object? Yep. You're
already ahead of the game!) All objects are similar to arrays in that they can hold more than a
single value. However, objects have several built-in properties. h e properties have either
i xed values (called constants) or values that change depending on the circumstances. Even
the Array object has a built-in property — length . It returns the number of elements in the
array. So, if you add the following two lines to the array program in the previous section,
you'll see how big the array is:
249
...
document . write ( fruit [ 1 ]);
//Add the following two lines
document . write ( “<br>” );
document . write ( fruit . length );
h e value of fruit.length is 4 — it's always one greater than the highest-numbered array
element because the length is the actual number of elements in the array beginning with the
value 1. (It's one-based instead of zero-based.)
Some properties of objects are called methods. A method is a function that does something in
relation to the object. For example, an Array object method is pop() . h e pop() method
returns the last element in the array. It's a way that you can assign a variable an object's
method — just as you can assign a variable a function. Let's i x up that program from the last
section again. h is time, the variable myFruit is assigned fruit.pop() . h at means
whatever is on the top of the array stack is removed. However, if used in a variable assign-
ment, it assigns the removed element to the variable as the following i x-up of the previous
snippet shows:
 
Search WWH ::




Custom Search