SOURCE

//用数组实现栈,栈是先进后出的线性结构
class Stack1{
    constructor(){
        this.stack = [];
    }
    isEmpty(){
    return    this.stack.length === 0;
    }

    push(item){
            return this.stack.push(item);
    }
    pop(){
        if(this.isEmpty()){
            return "stack is empty";
        }
        return this.stack.pop();
    }
    peek(){
        if(this.isEmpty()){
            return "stack is empty";
        }
        return this.stack[this.stack.length-1];
    }
    getLenth(){
        return this.stack.length;
    }
    destoryStack(){
        this.stack.splice(0,this.stack.length);
    }
    toString(){
        return this.stack.toString();
    }

}



//用对象实现栈
class Stack{
    constructor(){
        this.stack = {};
        this.length = 0;
    }
    isEmpty(){
        return this.length === 0;
    }
    pop(){
        if(this.isEmpty()) return "stack is empty";
        this.length--;
        let result = this.stack[this.length];
        delete this.stack[this.length];
        return result;
    }
    push(val){
        this.stack[this.length] = val;
        this.length++;
        return this.stack;
    }
    peek(){
        if(this.isEmpty()) return "stack is empty";
        return this.stack[this.length-1];
    }
    size(){
        return this.length;
    }
    clear(){
        // if(this.isEmpty()) return "stack is empty";
        // for(var key in this.stack){
        //     delete this.stack[key];
        // }
        while(!this.isEmpty()){
            this.pop();
        }
        this.length = 0;
    }
    toString(){
        let str ="";
        if(!this.isEmpty()){
            str = this.stack[0];
            for(let i = 1;i<this.length;i++){
                // str = `${str},${this.stack[i]}`;
               str= str+","+this.stack[i];
            }
        }
        return str;
    }

}


let s = new Stack();
let s1 = new Stack1();
s1.push(1);
s1.push(1);
s1.push(1);
s1.push(1);
s1.push(1);
s1.push(1);
console.log(s1.toString());
console.log(Object.getOwnPropertyNames(s));
console.log(Object.keys(s1));
console.log(s.isEmpty());
s.push(5);
s.push(2);
s.push(5);
s.push(2);
s.push(5);
s.push(2);
console.log(s.toString());
console 命令行工具 X clear

                    
>
console