//封装栈
function Stack(){
this.items = []
//栈的各种操作
//push压栈 声明在原型里
Stack.prototype.push = function(element){
this.items.push(element)
}
//pop出栈
Stack.prototype.pop = function(){
this.items.pop()
}
//peek查看栈顶元素
Stack.prototype.peek = function(){
return this.items[this.items.length - 1]
}
//isEmpty判断栈是不是为空
Stack.prototype.isEmpty = function(){
return this.items.length == 0
}
//size栈内元素的个数
Stack.prototype.size = function(){
return this.items.length
}
//toString栈内元素合并为字符串 中间以','分隔
Stack.prototype.toString = function(){
let resultString = ''
for(let i = 0; i < this.items.length; i++){
resultString += this.items[i] + ' '
}
return resultString
}
}
// let stack = new Stack()
// stack.push(1)
// stack.push(2)
// alert(stack.items)
//封装 10进制 -> 2进制 函数 dectobin
function dectobin(decNumber){
let stack = new Stack()
//把10进制数 除二 取余 压栈
while(decNumber > 0){
stack.push(decNumber % 2)
decNumber = Math.floor(decNumber / 2)
}
//出栈 把栈里的数字连成字符串 binString
var binString = ''
while(!stack.isEmpty){
binString += stack.pop()
}
return binString
}
//测试 dectobin 函数
alert(dectobin(15))
代码有两处问题
1、出栈方法要加 return
// pop出栈
Stack.prototype.pop = function(){
return this.items.pop()
}
2、stack.isEmpty是个方法,调用时加()
// pop出栈
while(!stack.isEmpty()){
binString += stack.pop()
}
3、(建议)不要在方法内进行原型链扩展
function Stack () {
this.items = []
}
//push压栈 声明在原型里
Stack.prototype.push = function(element){
this.items.push(element)
}
结果:
// 栈中的属性。js是弱类型语言,添加属性不用声明
this.items = [];
// 添加栈的操作
// push压栈 将某个元素添加进来
Stack.prototype.push=function(element){
this.items.push(element);
}
// pop出栈 返回栈顶元素并删除
Stack.prototype.pop=function(){
this.items.pop();
}
// peek查看栈顶元素 不会改变元素
Stack.prototype.peek=function(){
return this.items[this.items.length-1];
}
// isEmpty判空
Stack.prototype.isEmpty=function(){
return this.items.length==0;
}
// size 返回栈的个数
Stack.prototype.size=function(){
return this.items.length;
}
// toString 将栈的内容以字符串的形式返回
Stack.prototype.toString=function(){
var str="";
for(var i=0;i<this.items.length;i++){
str+=this.items[i]+"";
}
return str;
}
}
function DecToBdc(Dnumber){
var stack=new Stack();
while(Dnumber>0){
// 将余数压入栈中
stack.push(Dnumber%2)
// 获取整除后的结果(向下取整),作为下一次运算的数字
Dnumber=Math.floor(Dnumber/2);
}
// 定义变量接收出栈的余数
var str="";
while(!stack.isEmpty()){
str+=stack.items.pop();
}
return str;
}
console.log(DecToBdc(100));//1100100