栈的封装 (先进后出)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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.items.length; i++){
resultString += this.items[i] + ' '
}
return resultString
}
}
// 栈的使用
// var s = new Stack()
// s.push(20)
// s.push(10)
// s.push(100)
// s.push(77)
// console.log(s)
// s.pop()
// s.pop()
// console.log(s)
// console.log(s.peek())
// console.log(s.size())
// console.log(s.isEmpty())
// 函数 将 十进制转成 二级制
function dec2bin(decNumber){
// 1 定义栈对象
var stack = new Stack()
// 2 循环操作
while(decNumber > 0){
// 2.1 获取余数 并且放入到栈中
stack.push(decNumber % 2)
// 2.2 获取整除后的结果, 作为下一次运行的数字
decNumber = Math.floor(decNumber / 2)
}
// 3 从栈中取出 0 和 1
var binaryString = ''
while(!stack.isEmpty()){
binaryString += stack.pop()
}
return binaryString
}
var num = dec2bin(100)
console.log(num)
</script>
</body>
</html>
我是Eric,手机号是13522679763

浙公网安备 33010602011771号