- 栈是后进先出
stack: function () {
this.dataStore = []; //初始化为空
this.top = 0; //记录栈顶位置
this.pop = pop; //出栈
this.push = push; //入栈
this.peek = peek; //查看栈顶元素
this.length = length; //查看栈内元素总数
this.clear = clear; //清空栈
}
const _items = Symbol('stackItems');
class Stack {
constructor() {
this[_items] = [];
}
//添加元素到栈顶
push(element) {
this[_items].push(element);
}
// 从栈移除元素,移出的是最后添加进去的元素
pop() {
return this[_items].pop();
}
// 查看栈顶的元素
peek() {
return this[_items][this[_items].length - 1];
}
// 栈为空则返回 true ,非空 则返回 false
isEmpty() {
return this[_items].length === 0;
}
// 返回栈的长度
size() {
return this[_items].length;
}
// 清空栈
clear() {
this[_items] = [];
}
print() {
console.log(this.toString());
}
toString() {
return this[_items].toString();
}
}
const stack = new Stack();//初始化stack类
const objectSymbols = Object.getOwnPropertySymbols(stack);
console.log(objectSymbols.length); // 1
console.log(objectSymbols); // [Symbol()]
console.log(objectSymbols[0]); // Symbol()
stack[objectSymbols[0]].push(1);
stack.print(); // 5, 8, 1
网友评论