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标准入门第三版

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章