介绍栈结构操作的一些封装
1- 创建栈类 定义属性
// Method:和某一个对象实例有关系的 是方法
// Function: 函数
/ /封装栈类
function Stack(){
/ /栈中属性
this.items=[]
}
/ / 栈的使用
var s = new Stack
2. 对操作进行封装
//封装栈类
function Stack(){
//栈 中的一些属性
this.items=[]
//栈内操作
//1.将元素压入栈
Stack.prototype.push=function(element){
this.items.push(element)
}
//2.从栈中取出元素
Stack.prototype.pop=function(){
return this.items.pop()
}
//3.查看一下栈顶元素(不改变栈结构)
Stack.prototype.peek=function(){
return this.items[this.items.length-1]
}
//4.判断栈是否为空
Stack.prototype.isEmpty=function(){
return this.items.length==0
}
//5.获取栈中元素个数
Stack.prototype.size=function(){
return this.items.length
}
Stack.prototype.toString=function(){
var result =''
for(var i=0;i<this.items.length;i++){
result+=this.items[i]
}
return result
}
}
// 栈的使用
var s = new Stack
打印函数执行结果