微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript - 堆栈问题?

如何解决javascript - 堆栈问题?

当我控制台记录堆栈类时,我想查看已删除元素的堆栈,但程序只是告诉已删除但堆栈仍然相同,

输出

100 加到 0

200 加到 1

500 加到 2

400 添加到 3

800 加到 4

已移除 800 个

Stack {item: Array(5),count: 4} 我希望数组长度为 4

计数:4 项目:数组(5)

0:100 1:200 2:500 3:400 4:800 长度:5

class Stack {
  constructor() {
    this.item = [];
    this.count = 0;
  }

  // Add Elements to stack

  push(element) {
    this.item[this.count] = element;
    console.log(`${element} added to ${this.count}`);
    this.count += 1;
    return this.count - 1;
  }

  pop() {
    if (this.count === 0) return undefined;
    let deleteItem = this.item[this.count - 1];
    console.log(this.count);
    this.count -= 1;
    console.log(`${deleteItem} removed`);
    return deleteItem;
  }
}

let stack = new Stack();

stack.push(100);
stack.push(200);
stack.push(500);
stack.push(400);
stack.push(800);

stack.pop();

console.log(stack);

解决方法

pop类的Stack方法中,需要移除this.item的最后一个元素。请注意,JavaScript 数组已经具有 .push().pop() 方法,因此它们可以作为本机堆栈运行。

class Stack {
  constructor() {
    this.item = [];
    this.count = 0;
  }

  // Add Elements to stack

  push(element) {
    this.item[this.count] = element;
    console.log(`${element} added to ${this.count}`);
    this.count += 1;
    return this.count - 1;
  }

  pop() {
    if (this.count === 0) return undefined;
    let deleteItem = this.item.pop();
    console.log(this.count);
    this.count -= 1;
    console.log(`${deleteItem} removed`);
    return deleteItem;
  }
}

let stack = new Stack();

stack.push(100);
stack.push(200);
stack.push(500);
stack.push(400);
stack.push(800);

stack.pop();

console.log(stack);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。