JavaScript数组
- JS的数组是对象封装的
- 可以存放不同的数据类型
- 拥有自动扩容机制
- 中间插入和删除操作性能优于其他语言
Stack 栈
- 一种受限的线性结构
- 栈的应用:
- 函数调用栈
- A中调用B,B中调用C,C中调用D
- 函数依次入栈:A-> B -> C -> D
- 执行完出栈
- 栈的实现(基于数组):
- 属性:items: array = []
- 方法:
- push(element) 添加新元素到栈顶
- pop() 移除栈顶元素,并返回
- peek() 返回栈顶元素
- isEmpty() 判断栈是否空
- size() 返回栈的元素个数
- toString() 返回栈数据构成的字符串
- 代码:
const Stack = ()=>{
this.items = []
Stack.prototype.push=(element){
return this.items.push(element)
}
Stack.prototype.pop= ()=>{
return this.items.pop()
}
Stack.prototype.peek=()=>{
return this.items[this.items.length-1]
}
Stack.prototype.isEmpty=()=>{
return this.items.length === 0 ? true : false
}
Stack.prototype.size=()=>{
return this.items.length
}
Stack.prototype.toString=()=>{
let str = ''
for(const el in this.items){
str += el + ' '
}
return str
}
}