栈的封装
function Stack () {
this.items = []
Stack.prototype.push = function (element) {
this.items.push(element)
}
Stack.prototype.pop = function() {
return this.items.pop()
}
Stack.prototype.peek = () => {
return this.items[this.items.length - 1]
}
Stack.prototype.isEmpty = () => {
return this.items.length == 0
}
Stack.prototype.size = () => {
return this.items.length
}
Stack.prototype.toString = () => {
let resultString = ''
for(let item of this.items){
resultString += item
}
return resultString
}
}
modules.exports = Stack
10进制转2进制
<!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 src="./02_10进制转2进制.html"></script>
<script>
// 封装函数:将十进制转成二进制(十转二的运算最后倒叙取余的特点符合栈'后进先出')
let dec2bin = decNumber => {
// 1.定义一个栈对象,保存余数
var stack = new Stack()
// 2.循环操作
while(decNumber > 0) {
// 2.1获取余数并放入栈中
stack.push(decNumber % 2) // %取余符 ; / 除
// 2.2获取整除后的结果作为下一次运算的数字(floor:向下取整)
decNumber = Math.floor(decNumber / 2)
}
// 3.从栈中取出0和1
let binaryString = '';
while(stack.items.length != 0){
binaryString += stack.pop()
}
return binaryString
}
// 测试代码
console.log(dec2bin(4))
console.log(dec2bin(10))
</script>
</body>
</html>