Remove last element from Array(POP)
Object: Array
Method or Function: pop
Syntax: array_name.pop()
The pop() method removes the last element of anarray.
We have four elements in this array.Example: 1
<script type="text/javascript">
var names=new Array("One" , "Two", "Three", "Four");
for(i=0;i<names.length;i++)
{
document.write(names[i]+ "<br>");
}
</script>
From the output we see that last element is Four.
We want to remove Four.
Lets see the following example:
Example: 2
<script type="text/javascript">
var names=new Array("One" , "Two", "Three", "Four");
for(i=0;i<names.length;i++)
{
document.write(names[i]+ "<br>");
}
names.pop(); //Now our names array contains three elements.
document.write("Now we will not see last element <br><br>");
for(i=0;i<names.length;i++)
{
document.write(names[i]+ "<br>");
}
</script>
The pop() method also returns the element which is poped or removed.
Example: 3
var names=new Array("One" , "Two", "Three", "Four");
document.write(names.pop() + "<br>");
</script>
Here we see that element "Four" is returned.
No comments:
Post a Comment