This section provides a tutorial example on how to use array object methods like push(), pop(), unshift(), shift(), sort(), join(), etc.
To help you understand how some of the array object methods works, I wrote the following the JavaScript tutorial example,
Array_Object_Methods.html:
<html>
<!-- Array_Object_Methods.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Array Object Methods</title></head>
<body>
<pre>
<script type="text/javascript">
// Starting the array with 2 animals
var animals = new Array("Dog", "Cat");
// Push more animals to the end of the array
animals.push("Fox", "Fish");
// Pop off the last animal, fish, from the array
var fish = animals.pop();
// Push more animals to the front of ths array.
animals.unshift("Bird", "Eagle");
// Pop off the first animal, bird, from the array
var bird = animals.shift();
// Sort the array in ascending order
animals.sort();
// Reverse it in descending order
animals.reverse();
// Join all elements into a string
var all_four = animals.join(", ");
// Remove 2 of them starting from the 2nd one
animals.splice(1, 2);
// Join them again
var all_two = animals.join(", ");
// Display the result
document.write("Fish? " + fish + "\n");
document.write("Bird? " + bird + "\n");
document.write("All 4 animals? " + all_four + "\n");
document.write("All 2 animals? " + all_two + "\n");
</script>
</pre>
</body>
</html>
The output of this sample JavaScript is:
Fish? Fish
Bird? Bird
All 4 animals? Fox, Eagle, Dog, Cat
All 2 animals? Fox, Cat