Introduction
In the previous lesson, we learned how to use push() and pop() to add and remove items from the bottom of an array. We also learned how to use reverse.
In this tutorial we'll learn how to add and remove items from the top of an array. It's just as easy as adding them to the bottom. The very clever among you might've figured out that you can reverse() an array, add items using push() to the bottom, and reverse() again to bring the new items to the top of an array. Well, here's an easier way.
unshift( )
We'll be using this example in this tutorial. Notice that it is exactly like the previous example except it has two new buttons at the bottom below the black line. These are the new functions we'll be coding.
First lets add something to the top of the array. We use the unshift() method to do this. Here's the syntax:
array_name.unshift(what_to_add);
This is exactly like the push() syntax. The only difference is in the effect. An unshift()ed item will appear at the top of the array instead of the bottom.
The button in the example leads to a function I called "add_top()". Here's the function:
function add_top(){
var item = document.form1.inputbox.value;
dynamic_array.unshift(item);
document.form1.outputbox.value = dynamic_array;
}//ends add_top function
The first line assigns the value you typed in the textbox to the variable "item". The second line adjusts the array. It adds the value of "item" to the top of the array at index position [0]. The last line updates the textarea display.
shift( )
The shift() method removes the item at the top of an array. The syntax is just like the pop() method. Only the effect is different. The pop() method removes the last entry. The shift() method removes the first one.
array_name.shift()
The above is all that's needed to remove the first element of an array. The last button in the example leads to a function I called "remove_top()" that uses the shift() method to remove the top element of the array:
function remove_top(){
dynamic_array.shift();
document.form1.outputbox.value = dynamic_array;
}//ends remove_top function
The first line is the new one using the shift() method. This removes the first element in the array. The second line updates the textarea display.
Summary & Exercises
In this tutorial we learned how to add and remove elements from the top of an array using the unshift() and shift() methods. Try making the example from scratch twice. It takes a little practice before you easily remember which method does what.
Make a page sort of like a shopping cart that displays a list of items selected by checkboxes or clicking links. Use a textarea to make a dynamic list as in the examples. Now try drop down <select> menus.
To Next Advanced JavaScript Lesson
Back To Advanced JavaScript Index
|