class Stack {
constructor() {
this.item={}
this.count=0
}
//栈顶添加
push(item){
this.item[this.count]=item
this.count++
}
//删除
pop(){
if(this.isEmpty()){
return undefined
}
this.count--
const result = this.item[this.count]
delete this.item[this.count]
return result
}
//查看栈顶元素
peek() {
if(this.isEmpty()){
return undefined
}
return this.item[this.count]
}
//清空栈
clear() {
this.item = {}
this.count=0
}
//栈是否为空
isEmpty() {
return this.count===0
}
//查看栈长度
size(){
return this.count
}
//创建toString方法
toString() {
if (this.isEmpty()) {
return ``
}
let str = `${this.item[0]}`
for (let i =1;i < this.count; i++){
str+=`,${this.item[i]}`
}
return str
}
}
JavaScript不用数组实现栈的方式
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 1.使用ES6的Set进行去重 使用此方法非常简单,通俗易懂。该方法主要利用了Set内部结构的原理,然后通过Arr...
- 题目描述 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 在读题时,最开始没get到点,认...