栈是一种遵循后进先出(LIFO)原则的有序集合。新添加或待删除的元素都保存在栈的同一端,称作栈顶,另一端就叫栈底
创建一个类来表示数组
class Stack {
constructor(){
this.items = [];
}
push(element){
this.items.push(element)
}
pop(element){
this.items.pop();
}
peek(element){
return this.items[this.items.length-1]
}
isEmpty(){
return this.items.length === 0
}
clear(){
this.items = []
}
size(){
return this.items.length
}
}
let stack = new Stack();
stack.push(1)
console.log(stack.size())
console.log(stack.isEmpty())
创建一个基于Javascript对象的Stack类
class Stack {
constructor(){
this.items = [];
}
push(element){
this.items.push(element)
}
pop(){
this.items.pop();
}
peek(){
return this.items[this.items.length-1]
}
isEmpty(){
return this.items.length === 0
}
clear(){
this.items = []
}
size(){
return this.items.length
}
}
let stack = new Stack();
stack.push(1)
console.log(stack.size())
console.log(stack.isEmpty())
class Stack1{
constructor(){
this.count = 0;
this.items = {}
}
push(element){
this.items[this.count] = element;
this.count++
}
pop(){
if(this.isEmpty()){
return undefined
}
this.count--;
const result = this.items[this.count]
delete this.items[this.count]
return result;
}
peek(){
return this.items[this.count-1]
}
size(){
return this.count;
}
isEmpty(){
return this.count ===0
}
clear(){
this.count = 0;
this.items = {}
}
toString(){
if(this.isEmpty()){
return ''
};
let objString = `${this.items[0]}`;
for (let i=0;i<this.count;i++){
objString = `${objString},${this.items[i]}`
}
return objString
}
}
let a = new Stack1();
a.push(1);
console.log(Object.getOwnPropertyNames(a))
console.log(Object.keys(a))