基于js数组的Stack类
class Stack {
constructor() {
this.items = [1, 2, 3]
}
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
}
size() {
return this.items.length
}
clear() {
this.item = []
}
}
var stack = new Stack()
console.log(stack)
基于js对象的Stack类
class Stack {
constructor() {
this.count = 0
this.items = {}
}
push(element) {
this.items[this.count] = element
this.count++
}
size() {
return this.count
}
isEmpty() {
return this.count == 0
}
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]
}
clear() {
this.count = 0
this.items = {}
}
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
}
}
var stack = new Stack()
stack.push(3)
stack.push(4)
console.log(Object.getOwnPropertyNames(stack))
console.log(Object.keys(stack))
console.log(stack.count, stack.items)
|