JavaScript简单实现栈

2020-12-08  本文已影响0人  wxyzcctn

JavaScript简单实现栈主要是通过数组实现,以下是简单实现的代码

function Stack(){
    var items = [];
    // 在栈末尾添加项,对象可以直接调用
    this.push = function (element) {
        items.push(element)
    }
    // 删除并返回栈末尾的项
    this.pop = function () {
        return items.pop()
    }
    // 将栈转换为字符串返回
    this.toString = function () {
        return items.toString()
    }
    // 查看栈最后一项
    this.peek = function () {
        return items[items.length -1]
    }
    // 判断栈是否为空
    this.isEmpty = function () {
        return items.length === 0
    }
    // 清空栈
    this.clear = function () {
        items = []
    }
    // 返回栈长度
    this.size = function () {
        return items.length
    }
}
上一篇下一篇

猜你喜欢

热点阅读