More on JavaScript Array Objects - Shift() It Around
(Page 2 of 5 )
As stated in our beautiful table above, the shift() object is used to remove the first or left-most element in a given array, and return it. Below, we use it in a program that lists a bunch of fat guys, one of whom dies, and must be removed from the list:
<html>
<body>
<script type="text/javascript">
var fat = new Array(4);
fat[0] = "John Candy";
fat[1] = "Me";
fat[2] = "Valerie Bertinelli";
document.write("Here is a list of fat guys:");
document.write("<br />" + "<br />");
document.write(fat + "<br />" + "<br />");
document.write("This one died:" + "<br />");
document.write(fat.shift() + "<br />" + "<br />");
document.write("Leaving these:" + "<br />");
document.write(fat);
</script>
</body>
</html>
As you can see, John Candy has been removed from the array, resulting in this:
Here is a list of fat guys:
John Candy,Me,Valerie Bertinelli,
This one died:
John Candy
This one lost weight:
Me
Leaving these:
Valerie Bertinelli,
If I somehow miraculously lost all of my weight, we could also remove me from the list:
<html>
<body>
<script type="text/javascript">
var fat = new Array(4);
fat[0] = "John Candy";
fat[1] = "Me";
fat[2] = "Valerie Bertinelli";
document.write("Here is a list of fat guys:");
document.write("<br />" + "<br />");
document.write(fat + "<br />" + "<br />");
document.write("This one died:" + "<br />");
document.write(fat.shift() + "<br />" + "<br />");
document.write("This one lost weight:" + "<br />");
document.write(fat.shift() + "<br />" + "<br />");
document.write("Leaving these:" + "<br />");
document.write(fat);
</script>
</body>
</html>
Which results in:
Here is a list of fat guys:
John Candy,Me,Valerie Bertinelli,
This one died:
John Candy
This one lost weight:
Me
Leaving these:
Valerie Bertinelli,
Next: Slice Them Taters >>
More JavaScript Articles
More By James Payne