用JavaScript封装栈

用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(){},而是采用原型的方法,是因为通过prototype原型的方法相当于给整个类添加了方法,而this.push方式则仅是给某个实例添加方法。

用栈将十进制转为二进制

  • 因为我们习惯使用十进制,而计算机里面的所有内容都是用二进制数字表示的(0和1)
  • 可采用对十进制的数字进行除二取余法,将十进制转为二进制。
//函数:将十进制转为二进制
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;
}
发布了27 篇原创文章 · 获赞 5 · 访问量 6105

猜你喜欢

转载自blog.csdn.net/systempause/article/details/104530795