在棧的上一次筆記中,用的是基於數組實現的棧類,這次我是基於對象來實現棧的封裝,這次使用的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標準入門第三版