Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javascript-array JavaScript array push and pop

Related Tutorials


 
 

Share on Google+Share on Google+

JavaScript array push and pop

Advertisement
In this example we have created a simple html form which is taking input item value from the form and is adding as well as removing item from the array object.

JavaScript array push and pop

     

In this example we have created a simple html form which is taking input item value from the form and is adding as well as removing item from the array object.

In our JavaScript we have declared a dynamic array onto which we are going to perform the push and pop operations. We have created two buttons in this html form for pushing elements into the array and popping elements from the array.

 

 

 

 

function add_item(){
   var item = document.frm.inputbox.value;
   dynamic_array.push(item);
   document.frm.outputbox.value = dynamic_array;
   }

add_item() adds items into the array by the code dynamic_array.push(item);

function remove_item(){
  dynamic_array.pop();
  document.frm.outputbox.value = dynamic_array;
  }

remove_item() removes one element from the array object by using the method pop().

Following is the full example source code of push() and pop() method is as follows:

<html>
<head>
<title>JavaScript array push() and pop() example</title>
<script language="JavaScript">
var dynamic_array = new Array();
  function add_item(){
   var item = document.frm.inputbox.value;
   dynamic_array.push(item);
   document.frm.outputbox.value = dynamic_array;
   }
  function remove_item(){
  dynamic_array.pop();
  document.frm.outputbox.value = dynamic_array;
  }
</script>
</head>
<body>
<h2>Example of array's push() and pop()</h2>
<form name="frm">
<table width="245" border="0">
<tr>
<td width="91">Input Item </td>
<td width="144"><input type="text" name="inputbox" value=""/></td>
</tr>
<tr>
<td>Output Item </td>
<td><input type="text" name="outputbox" value=""/></td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<input type="button" onClick="add_item();" value="Push Item"/>
<input name="button" type="button" onClick="remove_item();" value="Pop Item"/>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>

Output is as follows:

"Push Item" button pushes item into the array.

"Pop Item" pops last element from the JavaScript array.

 Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 5, 2008

Related Tutorials

Discuss: JavaScript array push and pop  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Shekhar
July 29, 2011
Push Pop Example

Tutorial is good and easy to understand.
DMCA.com