栈是一种遵从后进先出 LIFO 原则的有序集合。
新添加或待删除的元素都保存在栈顶,另一端叫栈底。
新元素靠近栈顶,旧元素接近栈底。
栈用在编译器和内存中保存变量、方法调用。
栈的方法
- push(element) 添加元素到栈顶
- pop() 移除栈顶元素,返回被移除元素
- peek() 返回栈顶元素
- isEmpty() 是否空栈
- clear() 移除栈中所有元素
-
实现
基于数组实现
class Stack {constructor() {this.items = [];}push(element) {this.items.push(element);}pop() {return this.items.pop();}peek() {return this.items[this.items.length - 1];}isEmpty() {return this.items.length === 0;}clear() {this.items = [];}size() {return this.items.length;}toString() {return this.items.toString();}}
基于对象实现
class Stack {constructor() {this._count = 0;this._items = {};}push(element) {this._items[this._count] = element;this._count++;}pop() {if (this.isEmpty()) {return undefined;}this._count--;const result = this._items[this._count];delete this._items[this._count];return result;}peek() {if (this.isEmpty()) {return undefined;}return this._items[this._count - 1];}isEmpty() {return this._count === 0;}clear() {this._items = {};this._count = 0;}size() {return this._count;}toString() {if (this.isEmpty()) {return '';}let objString = `${this._items[0]}`;for (let i = 1; i < this._count; i++) {objString = `${objString}, ${this._items[i]}`;}return objString;}}
私有成员
使
_真正不能访问
- Symbol ,使用 Object.getOwnPropertySymbols() 可被破
WeakMap
const Stack = (function () {const _items = new WeakMap();return class Stack{constructor() {_items.set(this, []);}push(element) {_items.get(this).push(element);}pop() {return _items.get(this).pop();}peek() {return _items.get(this)[_items.get(this).length - 1];}isEmpty() {return _items.get(this).length === 0;}clear() {_items.get(this) = [];}size() {return _items.get(this).length;}toString() {return _items.get(this).toString();}}})();
