怎么在JavaScript中实现一个stack类?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
栈是一种“先进后出”的数据结构,原理如下图所示:

示例代码:
/*使用栈stack类的实现*/
function stack() {
this.dataStore = [];//保存栈内元素,初始化为一个空数组
this.top = 0;//栈顶位置,初始化为0
this.push = push;//入栈
this.pop = pop;//出栈
this.peek = peek;//查看栈顶元素
this.clear = clear;//清空栈
this.length = length;//栈内存放元素的个数
}
function push(element){
this.dataStore[this.top++] = element;
}
function pop(){
return this.dataStore[--this.top];
}
function peek(){
return this.dataStore[this.top-1];
}
function clear(){
this.top = 0;
}
function length(){
return this.top;
}
/*测试stack类的实现*/
var s = new stack();
s.push("aa");
s.push("bb");
s.push("cc");
console.log(s.length());//3
console.log(s.peek());//cc
var popped = s.pop();
console.log(popped);//cc
console.log(s.peek());//bb
这里使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:

看完上述内容,你们掌握怎么在JavaScript中实现一个stack类的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注天达云行业资讯频道,感谢各位的阅读!