1. function Stack() {
    2. this.dataStore = []; // 保存栈内元素
    3. this.top = 0; // 栈指针
    4. this.push = push;
    5. this.pop = pop;
    6. this.peek = peek;
    7. this.clear = clear;
    8. this.length = stackLength;
    9. }
    10. // 入栈
    11. function push(element) {
    12. this.dataStore[this.top++] = element;
    13. }
    14. // 出栈
    15. function pop() {
    16. return this.dataStore[--this.top];
    17. }
    18. // 返回栈顶元素
    19. function peek() {
    20. return this.dataStore[this.top - 1];
    21. }
    22. // 清栈
    23. function clear() {
    24. this.top = 0;
    25. }
    26. function stackLength() {
    27. return this.top;
    28. }
    29. var s = new Stack();
    30. s.push('一');
    31. s.push('二');
    32. s.push('三');
    33. s.push('四');
    34. console.log('len', s.length());
    35. console.log(s.pop())
    36. console.log(s.pop())
    37. console.log(s.length())