1. 栈
es5函数体实现
采用es5的创建对象的方法, 函数体内创建数据,修改数据的方法写在函数体的原型上
function Stack() {
this.count = 0; //栈的长度 也是items属性关键字
this.items = {}; // 栈的内容
}
Stack.prototype.push = function(item) { // 入栈 原型对象方法修改私有属性
this.items[this.count] = item;
this.count++;
}
Stack.prototype.pop = function() { // 出栈
this.count--;
var result = this.items[this.count];
delete this.items[this.count];
return result
}
Stack.prototype.toString = function() { // 查看栈的内容
var stackString = `${this.items[0]}`; // 采用es6的字面量
for(var i = 1; i < this.count; i++) {
stackString = `${stackString},${this.items[i]}`
}
return stackString
}
使用
var stack = new Stack() // 新建一个栈
stack.push('元素1') // 入栈
stack.push('元素2')
console.log(stack.toString()) // 输出 元素1,元素2
stack.pop() // 出栈
console.log(stack.toString()) // 输出 元素1
es6的class实现
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;
}
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;
}
}