栈(Stack)是限定只能在表的一端进行插入和删除操作的线性表。在表中,允许插入和删除的一端称作"栈顶(top)",不允许插入和删除的另一端称作"栈底(bottom)" 。
利用栈,可以做一些请求管理的操作,基于javascript中数组的特性,对其进一步的封装,结果如下:
var jStack = function(){
this.InitStack.apply(this,arguments);
}
jStack.prototype={
InitStack:function(){/*初始化栈*/
this.top = 0; /*栈顶指针*/
this.stack = [];
var args = arguments;
this.stacksize=255;/*默认栈的最大存储空间为255*/
if(args[1]){
if(this.isNumber(args[1])){
this.stacksize = args[1];
}else{
throw new Error('stacksize should be number!');
}
}
if(this.isJsType(args[0])){
if(this.isArray(args[0])){
for(var i=0,l=args[0].length;i<l&&i<this.stacksize;++i){
this.stack[this.stack.length]=args[0][i];
this.top++;
}
}else{ this.stack[0]=args[0];}
}else{ return;}
},
DestroyStack:function(){/*销毁栈*/
delete this.stack;
return true;
},
ClearStack:function(){/*清空栈*/
this.stack=[];
return true;
},
StackEmpty:function(){/*判断栈是否清空*/
if(this.StackLength()==0){return true;}
return false;
},
StackLength:function(){/*返回栈的长度*/
return this.stack.length;
},
GetTop:function(){/*获取栈顶元素*/
if(this.StackLength()>=1){
return this.stack[this.StackLength()-1];
}
},
Push:function(o){/*入栈*/
if(this.isJsType(o)){
if(this.stacksize==this.StackLength()){
this.stack.pop();
this.stack.push(o);
}else{
this.stack.push(o);
this.top++;
}
}else{
throw new Error("push failed!");
}
},
Pop:function(){/*出栈*/
if(this.StackLength()>=1){
this.top--;
return this.stack.pop();
}
return '';
},
getAllStack:function(){/*返回所有栈的元素*/
return this.stack;
},
StackTraverse:function(fn){/*用fn遍历栈的每个函数*/
var stackLength = this.StackLength();
var tempStack=[];
if(stackLength>=1&&this.isFunction(fn)){
try{
for(var i=0,l=stackLength;i<l;i++){
if(fn(this.stack[i])){
tempStack[tempStack.length]=this.stack[i];
}
}
}catch(e){
throw new Error("do failed the param have error!");
}finally{
return tempStack;
}
}else{
throw new Error('do failed because stack is empty or the param is not a function!');
}
},
getTopIndex:function(){
return this.top;
},
isJsType:function(o,type){/*判断元素是否是javascript类型,除undefined外*/
var types = ['number','string','boolean','object','function'];
for(var i in types){
if(types[i]===typeof o){
return true;
}
}
return false;
},
isNumber:function(o){/*判断是否是数字*/
if(typeof o === 'number'){
return true;
}
return false;
},
isFunction: function(o) {/*判断是否是函数*/
return typeof o === 'function';
},
isArray:function(o){/*判断是否是数组*/
if(o){
return this.isNumber(o.length)&&this.isFunction(o.splice);
}
return false;
}
}
var a = [1,2,3,4];
var jstack = new jStack(a,3);
alert(jstack.getAllStack());
jstack.StackTraverse(cc);
jstack.Push(22);
alert(jstack.getAllStack());
alert(jstack.StackTraverse(cc));
function cc(o){
return o>=2?true:false;
}