js封装实现的栈操作
栈
介绍
受限制的线性结构,后进先出
实现原理
使用到了js数组,以及其中的push() pop()方法
实现代码
<script> function Stack () { // 属性 this.items = [] //1.将元素压入栈 Stack.prototype.push = function (element) { this.items.push(element) } //2.从栈中取出元素 Stack.prototype.pop = function () { return this.items.pop() } //3.查看栈顶元素 Stack.prototype.peek = function () { return this.items[length - 1] } //4.判定栈是否为空 Stack.prototype.isEmpty = function () { return this.items.length == 0 } //5.获取栈中元素个数 Stack.prototype.size = function () { return this.items.length } //6.toString方法 Stack.prototype.toString = function () { var resultString = '' for(i=0;i<this.items.length;i++){ resultString += this.items[i] + ',' } return resultString } } //测试代码 var test = new Stack() test.push(10) test.push(34) test.push(45) test.push(30) test.push(13) test.pop() alert(test.toString()) </script>

浙公网安备 33010602011771号