js数据结构——栈
2017-01-22 00:00
78 查看
摘要: js数据结构——栈
由上段代码:
(1)使用动态原型模式创建对象
(2)利用数组,和数组的push()和pop()函数实现入栈和出栈。
function Stack(){ var items = []; //动态原型模式 if(typeof this.pop != "function"){ //入栈 Stack.prototype.push = function(element){ items.push(element); } //出栈 Stack.prototype.pop = function(){ return items.pop(); } //返回栈顶的元素 Stack.prototype.peek = function(){ return items[items.length-1]; } //判断是否栈空 Stack.prototype.isEmpty = function(){ return items.length == 0; } //移除栈里所有元素 Stack.prototype.clear = function(){ items = []; } //返回元素的个数 Stack.prototype.size = function(){ return items.length; } //打印栈里的元素 Stack.prototype.print = function(){ console.log(items.toString()); } } } var stack = new Stack(); //入栈5个元素 并打印 stack.push(5); stack.push(8); stack.push(1); stack.push(10); stack.push(7); stack.print(); //5,8,1,10,7 //输出栈的大小 console.log(stack.size()); //5 //取出栈顶元素并打印 console.log(stack.peek()); //7 stack.print(); //5,8,1,10,7 //出栈并打印 stack.pop(); stack.print(); //5,8,1,10 //清空栈并判空 stack.clear(); console.log(stack.isEmpty());//true
由上段代码:
(1)使用动态原型模式创建对象
(2)利用数组,和数组的push()和pop()函数实现入栈和出栈。
相关文章推荐
- JS实现弹出层锁定窗口(改进版)
- js 身份证验证
- JS 文件本身编码转换 图文教程
- JS 图片缩放效果代码
- Js获取当前日期时间及其它操作
- js天气预报 js版天气预报接口
- JS Cookies 函数 通过IE6、IE7,IE8,FF,Safari,Chrome,Opera
- js动态改变iframe的src属性
- Node.js基础入门实例讲解
- JS_应用对象的复制
- js时间选择控件
- JS全选checkbox
- JS放在博客里面运行
- Delphi中TWebBrowser中注入Js
- [js] Javascript中的一种深复制实现
- 在发送ajax请求时加时间戳或者随机数去除js缓存
- 【转】javascript深入理解js闭包
- 使用js实现页面跳转的几种方式
- FineUI4.0以后如何调用JS事件