JavaScript数据结构与算法--栈(下)

在栈的上一次笔记中,用的是基于数组实现的栈类,这次我是基于对象来实现栈的封装,这次使用的ES6增加的class类的语法,其实没有啥,就是把function函数换成的class实现类,更加快捷。
基于数组实现栈可参照我的上一篇博客:JavaScript数据结构与算法–栈(上)

基于JavaScript对象创建一个栈

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        //创建栈类(es6语法)
        class MyStack{
            constructor(){
                this.count = 0;
                this.items = {};
            }
            //向栈中插入元素(注意我这个方法只允许一次插入一个元素)
            push(element){
                this.items[this.count] = element;
                this.count++;
            }
            //验证一个栈是否为空
            isEmpty(){
                return this.count === 0;
            }
            //查看栈的大小
            size(){
                return this.count;
            }
            //从栈中删除元素
            pop(){
                if(this.isEmpty()){
                    return undefined;
                }
                this.count--;
                const result = this.items[this.count];
                delete this.items[this.count];
                return result;
            }
            //查看栈顶的值
            peek(){
                if(this.isEmpty()){
                    return undefined;
                }
                return this.items[this.count - 1];
            }
            //清空栈中所有元素
            clear(){
                this.items = {};
                this.count = 0;
            }
        }
        //使用栈
        const s = new MyStack();
        s.push(10);
        s.push(20);
        s.push(30);
        console.log(s.peek()); //30
        console.log(s.isEmpty()); //false
        console.log(s.size()); //3

        s.pop(); 
        console.log(s.peek()); //20
        console.log(s.size()); //2
        s.clear(); 
        console.log(s.isEmpty()) //true

    </script>
</body>
</html>

上面就是一个栈的完整实现过程。
关于class(类)的详细学习可学习阮一峰的ES6标准入门第三版

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值