Friday, April 25, 2014

Javascript example: add and remove elements from Array

This example show how to add/remove elements from array, using Javascript:

  • push(): Add new elements to the end of an array
  • pop(): Remove the last element of an array
  • unshift(): Add new elements to the beginning of an array
  • shift(): Remove the first element of an array
<!DOCTYPE html>
<html>
<body onload="doit();">

<h1>mobile-web-app.blogspot.com</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3a"></p>
<p id="p3b"></p>
<p id="p4a"></p>
<p id="p4b"></p>
<p id="p5"></p>
 
<script type="text/javascript">
 
function doit()
{ var array = ['A', 'B', 'C', 'D'];
 document.getElementById("p1").innerHTML=array;
 
 array.push('E'); //Add element in end
 document.getElementById("p2").innerHTML="push('E'): " + array;
 
 var eleFirst = array.shift(); //remove first element
 document.getElementById("p3a").innerHTML="array.shift(): " + eleFirst;
 document.getElementById("p3b").innerHTML=array;
 
 var eleLast = array.pop();  //remove last element
 document.getElementById("p4a").innerHTML="array.pop(): " + eleLast;
 document.getElementById("p4b").innerHTML=array;
 
 array.unshift('a'); //Add element in front
 document.getElementById("p5").innerHTML="unshift('a'): " + array;
}
 
</script>
</body>
</html>


No comments:

Post a Comment