JavaScript栈
2015-11-05 00:00
766 查看
摘要: JavaScript栈
In computer science, a stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the last element that was added.
什么是栈?
栈是一种遵循后进先出(Last in , first out)原则的有序组合。它类似于数组,但是添加和删除元素时有更加灵活的控制。新添加的或者待删除的元素都保存在栈的末尾,即栈顶。另一端就是栈底。譬如,餐厅里的一摞盘子,最上面的盘子是最后放上去的,第一个放上去的盘子被压在最底端。即,新元素都靠近栈顶,旧元素都靠近栈底。在计算机内部,栈被用于在编译器或者内存中保存变量和方法调用。如下创建了一个类来表示栈。In computer science, a stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the last element that was added.
JavaScript如何定义栈?
function Stack() {//各种属性、方法 var items = [];//依然选择数组来保存元素 this.push = function(element){//添加元素到栈顶,这里使用了数组的push方法 items.push(element); }; this.pop = function(){//移除栈顶元素,并且返回该元素 return items.pop(); }; this.peek = function(){//仅仅返回栈顶元素,类似于查询的功能,不对栈做任何修改 return items[items.length-1]; }; this.isEmpty = function(){//逻辑判断的功能,如果栈里为空,返回true return items.length == 0; }; this.size = function(){//返回栈里的元素的个数,即判断内部数组的长度是否为0 return items.length; }; this.clear = function(){//清空栈的内容 items = []; }; this.print = function(){ console.log(items.toString()); }; this.toString = function(){ return items.toString(); }; }
JavaScript如何使用栈?
那么,就用一下这个栈吧。以下是使用栈的代码。var stack = new Stack(); console.log(stack.isEmpty()); //outputs true stack.push(5); stack.push(8); console.log(stack.peek()); // outputs 8 stack.push(11); console.log(stack.size()); // outputs 3 console.log(stack.isEmpty()); //outputs false stack.push(15); stack.pop(); stack.pop(); console.log(stack.size()); // outputs 2 stack.print(); // outputs [5, 8]
相关文章推荐
- js鼠标滑过导航菜单出现相应的内容
- JavaScript中没有块级作用域程序举例例证
- javascript接口鸭式辨型法实现
- 第一个 mac 程序 Create-JSON-Model
- Jsoup获取全国地区数据(省市县镇村)(续) 纯干货分享
- JavaScript中的this
- 彻底理解JavaScript原型
- javascript(六)正则表达式
- javascript(五)undefined false 字符串变量
- 上传文件中使用ajaxfileupload.js碰到的问题
- 在IE6/7中兼容JSON.parse和JSON.stringify
- JavaScript中声明全局变量的三种方式(包括显示和隐式)
- JSP九大内置对象的作用和用法总结
- 上传文件中使用ajaxfileupload.js碰到的问题
- JS获取EL表达式的值
- jsp中类似gridview的功能
- javascript代码片段
- js父子窗口(二)
- js 父子窗口(一)
- js小例子(简单模糊匹配输入信息)