利用数组封装栈 同时使用栈来构造将十进制转换成二级制的函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>栈的封装</title>
<script>
function Stack(){
this.items =[];
//栈的一些功能,可以利用数组的一些方法
//入栈 push
//复习prototype
Stack.prototype.push=function(element){
this.items.push(element);
}
//出栈pop 并返回元素
Stack.prototype.pop=function(){
return this.items.pop();
}
//查看栈顶元素(不作任何其他操作)
Stack.prototype.peek=function(){
return this.items[this.items.length-1];
}
//判断栈是否为空
Stack.prototype.isEmpty=function(){
return this.items.length==0;
}
//获取栈中元素的个数
Stack.prototype.size=function(){
return this.items.length;
}
//toString方法
Stack.prototype.toString=function(){
var string='';
for(var i=0;i<this.items.length;i++){
string+=this.items[i]+' ';
}
return string;
}
}
var stack = new Stack();
//构造函数的执行过程:1)立即创建一个对象2)将该对象设置为函数中的this
//在函数中可以用this引用这个新的对象3)执行函数中的代码
//将新建的对象作为返回值返回
// stack.push(true);
// stack.push(123);
// stack.push("hi there");
// alert(stack.pop());
// alert(stack.size());
// alert(stack.isEmpty());
// alert(stack.peek());
// alert(stack.toString());
// alert(stack);
//将十进制数转换成二进制数 利用栈
function dec2bin(decNumber){
var sta = new Stack();
while(decNumber>0){
sta.push(decNumber%2);
decNumber=Math.floor(decNumber/2);
}
var str='';
while(!sta.isEmpty()){
str+=sta.pop();
}
alert(str);
}
dec2bin(100);
</script>
</head>
<body>
</body>
</html>