JavaScript基础(5) -- js堆栈

  1. function stack(){  

  2.       if(this.top==undefined){  

  3.       //初始化堆栈的顶部指针和数据存放域  

  4.             this.top=0;  

  5.             this.unit=new Array();  

  6.       }  

  7.       this.push=function(pushvalue){  

  8.       //定义压入堆栈的方法              

  9.             this.unit[this.top]=pushvalue;  

  10.             this.top+=1;              

  11.       }  

  12.       this.readAllElements=function(){  

  13.       //定义读取所有数据的方法  

  14.             if(this.top==0){  

  15.                   alert("当前栈空,无法读取数据");  

  16.                   return("");  

  17.             }  

  18.             var count=0;  

  19.             var outStr="";  

  20.                           

  21.             for(count=0;count<this.top;count++){  

  22.                   outStr+=this.unit[count]+",";  

  23.             }              

  24.             return(outStr);  

  25.       }  

  26.       this.pop=function(){  

  27.       //定义弹出堆栈的方法  

  28.             if(this.top==0){  

  29.                   alert("当前栈空,无法弹出数据");  

  30.                   return("");  

  31.             }  

  32.             var      popTo=this.unit[this.top-1];  

  33.             this.top--;  

  34.             return(popTo);  

  35.             /* 从堆栈弹出数据,顶部指针减一,不过这里没有做到资源的释放,也 

  36.             就是说数据仍然存在于this.unit的数组中,只不过无法访问罢了。目前 

  37.             我也没想到好的办法解决。*/  

  38.       }  

  39. }  

posted @ 2016-12-08 20:09  稼轩  阅读(185)  评论(0编辑  收藏  举报