JavaScriptを使用してスタックパッケージ
// 封装栈
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.check = 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;
// 方法二:
return this.items.join(' ');
};
}
理由は使用されないthis.push=function(){}
代わりに、プロトタイプの方法を使用するには、クラス全体と同等のメソッドプロトタイププロトタイプによってメソッドを追加することで、this.push唯一の方法は、インスタンスメソッドを追加することです。
バイナリへのスタック小数
- 私たちは、小数点を使用に慣れていると、コンピュータ内のすべてのコンテンツは、バイナリ数字(0と1)で表されているので
- 小数は、2つの加算法、小数にバイナリを法とするために用いました。
//函数:将十进制转为二进制
function dec2bin(decNumber){
// 1.定义栈对象
var stack = new Stack();
while(decNumber > 0){
stack.push(decNumber % 2);
decNumber = Math.floor(decNumber / 2);
console.log(decNumber)
}
var binaryString = '';
while(!stack.isEmpty()){
binaryString += stack.pop();
}
return binaryString;
}