栈是一种遵循后进先出(LIFO)原则的有序集合。新添加或待删除的元素都保存在栈的同一端,称作栈顶,另一端就叫栈底
    image.png
    创建一个类来表示数组

    1. class Stack {
    2. constructor(){
    3. this.items = [];
    4. }
    5. push(element){
    6. this.items.push(element)
    7. }
    8. pop(element){
    9. this.items.pop();
    10. }
    11. peek(element){
    12. return this.items[this.items.length-1]
    13. }
    14. isEmpty(){
    15. return this.items.length === 0
    16. }
    17. clear(){
    18. this.items = []
    19. }
    20. size(){
    21. return this.items.length
    22. }
    23. }
    24. let stack = new Stack();
    25. stack.push(1)
    26. console.log(stack.size())
    27. console.log(stack.isEmpty())

    创建一个基于Javascript对象的Stack类

    1. class Stack {
    2. constructor(){
    3. this.items = [];
    4. }
    5. push(element){
    6. this.items.push(element)
    7. }
    8. pop(){
    9. this.items.pop();
    10. }
    11. peek(){
    12. return this.items[this.items.length-1]
    13. }
    14. isEmpty(){
    15. return this.items.length === 0
    16. }
    17. clear(){
    18. this.items = []
    19. }
    20. size(){
    21. return this.items.length
    22. }
    23. }
    24. let stack = new Stack();
    25. stack.push(1)
    26. console.log(stack.size())
    27. console.log(stack.isEmpty())
    28. class Stack1{
    29. constructor(){
    30. this.count = 0;
    31. this.items = {}
    32. }
    33. push(element){
    34. this.items[this.count] = element;
    35. this.count++
    36. }
    37. pop(){
    38. if(this.isEmpty()){
    39. return undefined
    40. }
    41. this.count--;
    42. const result = this.items[this.count]
    43. delete this.items[this.count]
    44. return result;
    45. }
    46. peek(){
    47. return this.items[this.count-1]
    48. }
    49. size(){
    50. return this.count;
    51. }
    52. isEmpty(){
    53. return this.count ===0
    54. }
    55. clear(){
    56. this.count = 0;
    57. this.items = {}
    58. }
    59. toString(){
    60. if(this.isEmpty()){
    61. return ''
    62. };
    63. let objString = `${this.items[0]}`;
    64. for (let i=0;i<this.count;i++){
    65. objString = `${objString},${this.items[i]}`
    66. }
    67. return objString
    68. }
    69. }
    70. let a = new Stack1();
    71. a.push(1);
    72. console.log(Object.getOwnPropertyNames(a))
    73. console.log(Object.keys(a))

    https://juejin.cn/post/6844903757973569544