之前一堆提到了栈,只要能够对其栈和队列的区别,其实也是很简单的,结果如下:
var jQueue = function(){
this.InitQueue.apply(this,arguments);
}
jQueue.prototype={
InitQueue:function(){/*初始化队列*/
this.front = this.rear = 0;/*队列的头指针和尾指针*/
this.queue=[];
var args = arguments;
if(this.isJsType(args[0])){
if(this.isArray(args[0])){
for(var i=0,l=args[0].length;i<l;++i){
this.queue[this.rear++]=args[0][i];
}
}else{ this.queue[0]=args[0];}
}else{ return;}
},
DestroyQueue:function(){/*销毁队列*/
delete this.queue;
return true;
},
ClearQueue:function(){/*清空队列*/
this.queue = [];
return true;
},
QueueEmpty:function(){/*判断对了是否为空*/
if(this.QueueLength()==0){return true;}
return false;
},
QueueLength:function(){/*队列的长度*/
return this.rear;
},
GetHead:function(){/*获取队列头元素*/
if(this.QueueLength()>=1){
return this.queue[0];
}
return '';
},
getAllQueue:function(){
return this.queue;
},
EnQueue:function(o){/*在当前队列的尾元素之后插入元素*/
if(this.isJsType(o)){
++this.rear;
this.queue.push(o);
}else{
throw new Error('the param is undefined!');
}
},
DeQueue:function(){/*删除当前队列Q中的头元素,并返回*/
if(this.QueueLength()>1){
--this.rear;
return this.queue.shift();
}
return '';
},
QueueTraverse:function(fn){/*遍历队列,按一定规则返回队列的元素*/
var queueLength = this.QueueLength();
var tempQueue=[];
if(queueLength>=1&&this.isFunction(fn)){
try{
for(var i=0,l=queueLength;i<l;i++){
if(fn(this.queue[i])){
tempQueue[tempQueue.length]=this.queue[i];
}
}
}catch(e){
throw new Error("do failed the param have error!");
}finally{
return tempQueue;
}
}else{
throw new Error('do failed because stack is empty or the param is not a function!');
}
},
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 = [{a:2,b:3},{a:4,b:3},{a:5,b:3}];
var jqueue = new jQueue(a);
var aa = jqueue.QueueTraverse(tt);
for(var i in aa){
for(var j in aa[i]){
alert(aa[i][j]);
}
}
function tt(o){
return o.a>=4?true:false;
}