美文网首页
JavaScript简单实现栈

JavaScript简单实现栈

作者: wxyzcctn | 来源:发表于2020-12-08 23:34 被阅读0次

    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
        }
    }
    

    相关文章

      网友评论

          本文标题:JavaScript简单实现栈

          本文链接:https://www.haomeiwen.com/subject/vldcgktx.html