JS 栈

劳彦
2023-12-01

ES5写法:
function Stack(){

	let item = [];
	
	this.push = function(element){
		
		item.push(element);
	
	}
	
	this.pop = function(){
		
		return item.pop();
	
	}
	
	this.peek = function(){
		
		return item[item.length - 1]
	
	}
	
	this.isEmpty = function(){
		
		return item.length == 0;
	
	}
	
	this.size = function(){
		
		return item.length;
	
	}
	
	this.clear = function(){
		
		return item = [] ;
	
	}
	
	this.print = function(){
		
		console.log(item.toString());
	
	}

}

ES6写法:
let Stack = (function(){

	let items = new WeakMap();
	
	class Stack{
				
		constructor(){
			
			items.set(this, []);
		
		}
		
		push(element){
					
			let s = itmes.get(this);
		
			s.push(element);
		
		}
				
		pop(){
			
			let s = items.get(this);
			
			return s.pop();
		
		}

		peek(){
			
			let s = items.get(this);
			
			return s[s.length - 1]
		
		}
		
		isEmpty(){
			
			let s = items.get(this);
					
			return s.length == 0;
		
		}
		
		size(){
			
			let s = items.get(this);
			
			return s.length;
		
		}
		
		print(){
	
			let s = items.get(this);
	
			return s.toString();
		
		}
	
	}

	return Stack;

})()
 类似资料: