Implementing special types of arrays



Using the pop and push methods

The pop and push methods provide stack functionality. The push method appends the specified items to the end of the array. The pop method removes the last item from the array.

The following code demostrates this:

<body>
<input type="submit" onclick="PushPop()" value="Push & Pop Methods" /><br />
<div id="#div1"> </div>
<div id="#div2"> </div>
<!-- PUSH & POP METHODS-->
<script type="text/javascript">
  var PushPop = function () {
      var sports = new Array();
      sports.push('soccer', 'basketball', 'hockey');
      document.getElementById("#div1").innerHTML =
          ("Array After PUSH : " + "[" + sports.toString() + "]");
  
      sports.push('football');
      document.getElementById("#div2").innerHTML =
          ("Array After PUSH('football') : " + "[" + sports.toString() + "]");
  
      var nextSport = sports.pop();
      document.getElementById("#div3").innerHTML =
          ("Array After POP : " + "[" + sports.toString() + "]"); 
  }
</script>
</body>

Using the shift and unshift methods

The shift and unshift methods work in the exact opposite way from the pop and push methods.

The shift method removes and returns the first element of the array, whereas the unshift method inserts new elements at the beginning of the array.

The following code uses the shift and unshift methods:

<body>
<input type="submit" onclick="ShiftUnshift()" value="Shift & Unshift Methods" /><br />
<div id="#div1"> </div>
<div id="#div2"> </div>
<!-- SHIFT & UNSHIFT METHODS-->
<script type="text/javascript">
  var step2 = function () {
     var sports = new Array();
     sports.unshift('soccer', 'basketball', 'hockey');
     document.getElementById("#div1").innerHTML =
        ("Array After UNSHIFT : " + "[" + sports.toString() + "]");
     
     sports.unshift('football');
     document.getElementById("#div2").innerHTML =
        ("Array After UNSHIFT('football') : " + "[" + sports.toString() + "]");
     
     var nextSport = sports.shift();
     document.getElementById("#div3").innerHTML =
        ("AFTER SHIFT : " + nextSport + " <br>ARRAY sports : " + sports.toString());
  }
</script>
</body>

PROMOTIONS