JavaScript实现基于数组的栈

 

class StackArray {
  constructor() {
    this.items = [];
  }
  push(element) {
    this.items.push(element);
  }

  pop() {
    return this.items.pop();
  }

  peek() {
  return this.items[this.items.length-1];   //如果数组下标为-1,返回值为undefined
  }

  isEmpty() {
    return this.items.length === 0;
  }

  size() {
    return this.items.length;
  }

  clear() {
    this.items = [];   //指向一个新的空数组,原来的数组空间会被JavaScript垃圾会后机制自动回收
  }

  toArray() {
    return this.items;
  }

  toString() {
    return this.items.toString();
  }
}

 

posted @ 2020-10-26 23:14  WP-WangPin  阅读(100)  评论(0编辑  收藏  举报