Javascript 使用ES6创建Minstack

Javascript 使用ES6创建Minstack,javascript,stack,Javascript,Stack,我试图为伟大的MinStack问题提供解决方案,并尝试使用ES6符号编写它。我已经能够使用ES5类表示法完成这个问题,但我无法找出我的代码的错误。由于某些原因,在MinStack中的push方法中,传入的值变得未定义。因此,当我打印出min.\u min.storage时,所有的值都是未定义的。非常感谢您的帮助,并祝您愉快 class Stack { constructor(capacity) { this.capacity = capacity; this.count

我试图为伟大的MinStack问题提供解决方案,并尝试使用ES6符号编写它。我已经能够使用ES5类表示法完成这个问题,但我无法找出我的代码的错误。由于某些原因,在MinStack中的push方法中,传入的值变得未定义。因此,当我打印出min.\u min.storage时,所有的值都是未定义的。非常感谢您的帮助,并祝您愉快

class Stack {
    constructor(capacity) {
    this.capacity = capacity;
    this.count = 0;
    this.storage = {};
  }

   push(value) {
     console.log('here is this and your value', this, value) //value is undefined when _.min.push(value) is called
    if (this.count === this.capacity) {
      return 'Max capacity already reached. Remove element before adding a new one.';
    } else {
      this.storage[this.count++] = value;
    }
 }
// Time complexity: 0(1);

  pop() {
    var poppedElement = this.storage[--this.count];
    delete this.storage[this.count];
    if (this.count < 0) {
      this.count = 0;
    }
    return poppedElement;
  };
  // Time complexity: 0(1)

  peek() {
    return this.storage[this.count - 1];
  };
  // Time complexity: 0(1)

  count() {
    return this.count;
};
}
// Time complexity: 0(1)


//1.
class MinStack extends Stack {
  constructor(capacity) {
    super(capacity);
    this._min = new Stack(capacity);
  }

  push(value) {
    if (this.count < this.capacity) {
      if (value < this._min.peek()) {
        this._min.push(value);
      } else {
        this._min.push(this._min.peek());
      }
      this.storage[this.count++] = value;
      return this.count;
    }
  }

  pop() {
    const poppedElement = this.storage[--this.count];
    this._min.pop();
    delete this.storage[this.count];
    if (this.count < 0) {
      this.count = 0;
    }
    return poppedElement;
  }

  min() {
    return this._min.peek();
  }

  peek() {
    return this.storage[this.count - 1];
  }

  count() {
    return this.count;
  }
}

var min = new MinStack(6);
min.push(1);
min.push(2)
min.push(1)
min.push(0)
min.push(3)
min.push(5)
console.log(min);
console.log(min.min()) //undefined
类堆栈{
建造商(容量){
这个。容量=容量;
此值为0.count;
this.storage={};
}
推送(值){
console.log('这里是this和您的值',this,value)//调用u.min.push(value)时,值未定义
if(this.count==this.capacity){
return“已达到最大容量。请在添加新元素之前删除元素。”;
}否则{
this.storage[this.count++]=值;
}
}
//时间复杂度:0(1);
流行音乐(){
var poppedElement=this.storage[--this.count];
删除此.storage[this.count];
if(this.count<0){
此值为0.count;
}
退换货;
};
//时间复杂度:0(1)
peek(){
返回此.storage[this.count-1];
};
//时间复杂度:0(1)
计数(){
返回这个.count;
};
}
//时间复杂度:0(1)
//1.
类MinStack扩展堆栈{
建造商(容量){
超级(容量);
此值。_min=新堆栈(容量);
}
推送(值){
if(this.count
这是因为您的
This.\u min.peek()
函数首先返回未定义的。您必须确保您的存储至少有一个值。@Simon很抱歉这么晚才回复!非常感谢你的帮助!