<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>栈的封装</title>
</head>
<body>
<script>
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
}
//6.toString方法
Stack.prototype.toString = function(){
var resultstring = ' '
for(var i = 0; i < this.length; i++){
resultstring += this.items[i] + ' '
}
return resultstring
}
}
//栈的使用
var s = new Stack()
s.push(10)
s.push(20)
alert(s)
s.pop()
alert(s)
</script>
</body>
</html>