JavaScript中的栈数据结构可以用数组来进行封装

封装栈类

function Stack() {

    // 栈中的属性
    this.items = []

    //栈的相关方法
    //往原型上注册方法让所有实例对象共享,节省内存

    //1.将元素压入栈
    Stack.prototype.push = function(element) {
        this.items.push(element)
    }

    //2.从栈中取出元素  arr.pop删除数组最后一个元素并返回这个元素
    Stack.prototype.pop = function() {
        return this.items.pop()
    }

    //3.查看栈顶元素
    Stack.prototype.peek = 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 stringStack = ''
        for (let i = 0; i < this.items.length; i++) {
            stringStack += this.items[i] + ' '
        }

        return stringStack
    }
}

栈的使用


s.push(5)
s.push(15)
s.push(47)
s.push(5)
s.pop()

console.log(s.toString());//5 15 47 
console.log(s.isEmpty());//false
console.log(s.size());//3

栈的运用之十进制转换二进制

    var s = new Stack()

    while (decNum > 0) {
        s.push(decNum % 2)
        decNum = Math.floor(decNum / 2)
    }
    var bin = ''
    while (!s.isEmpty()) {
        bin += s.pop()
    }

    return bin
}
console.log(dec2num(100));//1100100