El paquete de pila con JavaScript

El paquete de pila con 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(' ');
        };
    }

La razón no se utiliza this.push=function(){}, en lugar de utilizar el método prototipo es que equivale a toda la clase para agregar un método mediante el método de prototipo prototipo, y this.push única forma es añadir un método de instancia.

decimal a binario pila

  • Debido a que estamos acostumbrados a usar el decimal y todos los contenidos dentro de la computadora representados por los dígitos binarios (0 y 1)
  • Se emplearon números decimales a modulo dos método de adición, el binario en decimal.
//函数:将十进制转为二进制
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;
}
Publicado 27 artículos originales · ganado elogios 5 · Vistas 6105

Supongo que te gusta

Origin blog.csdn.net/systempause/article/details/104530795
Recomendado
Clasificación