下面我们通过一个简单的案例来熟悉掌握js中栈的常见操作!
<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
function Stack(){
//栈中的属性
this.items=[]
// 栈的相关操作
// 1.将元素压入栈,两种方法!第二种方法好啊!,第一种方法是对某个实例添加了方法,第二种方法是对某个类添加了方法!共享!
// this.push=function (){}
Stack.prototype.push= (element)=>{
this.items.push(element)
}
// 2.将栈中的元素取出来
Stack.prototype.pop=()=>{
return this.items.pop()
}
// 3.查看栈中的元素
Stack.prototype.peek=()=>{
return this.items[this.items.length-1]
}
// 4.判断栈是否空
Stack.prototype.isEmpty=()=>{
return this.items.length===0
}
// 5.获取栈中元素的个数
Stack.prototype.size=()=>{
return this.items.length
}
// 6.toString的方法
Stack.prototype.toString=()=>{
// 20 10 12 8 7
let resultString=''
for (let i=0;i
resultString +=this.items[i]+' '
}
return resultString
}
}
// 栈的使用
// 验证!
let s=new Stack()
s.push(20)
s.push(10)
s.push(100)
s.push(77)
alert(s)
s.pop()
s.pop()
alert(s)
alert(s.peek())
alert(s.isEmpty())
alert(s.size())
</html>
结果显示:
成功实现!