栈(LIFO)的规则:先进后出,后进先出
代码:
<!DOCTYPE html>
<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>
<div id="app"></div>
<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(){
let str = ""
for(let i = 0; i < this.items.length; i++){
str += this.items[i] + " "
}
return str
}
}
//将十进制转成二进制
function dec2bin(decNumber){
//栈的使用
let stack = new Stack()
let binaryStr = ''
while(decNumber > 0){
stack.push(decNumber % 2)
decNumber = Math.floor(decNumber / 2)
}
while(!stack.isEmpty()){
binaryStr += stack.pop()
}
return binaryStr
}
alert(dec2bin(10))
</script>
</body>
</html>
结果: