javascript - JS 实现栈时clear方法不清楚

标签 javascript data-structures stack

我最近在看这本书chapter ,其中解释了如何在 JS 中创建堆栈。这是代码:

function Stack() {
   this.dataStore = [];
   this.top = 0;
   this.push = push;
   this.pop = pop;
   this.peek = peek;
   this.clear = clear;
   this.length = length;
}

function push(element) {
   this.dataStore[this.top++] = element;
}

function peek() {
   return this.dataStore[this.top-1];
}

function pop() {
   return this.dataStore[--this.top];
}

function clear() {
   this.top = 0;
}

function length() {
   return this.top;
}

我无法理解 clear() 方法。为什么将 top 设置为 0 会清除数组?我也期待着 this.dataStore.length = 0 行。似乎将 top 设置为 0 只会更改指针,而 dataStore 不会改变,这意味着进一步的操作只会覆盖以前的 dataStore 值。谁能解释一下发生了什么事吗?谢谢!

最佳答案

It seems like setting the top to 0 only changes the pointer and the dataStore is unchanged, meaning that further operations would just overwrite the previous dataStore values.

你说得完全正确。我同意这种行为可能是不可取的。

相反,我建议如下:

function Stack() {
   this.dataStore = [];
}
Object.assign(Stack.prototype, {
  push: function(element) {
    this.dataStore.push(element);
  },
  peek: function() {
    return this.dataStore[this.dataStore.length-1];
  },
  pop: function() {
    return this.dataStore.pop();
  },
  clear: function() {
    this.dataStore.length = 0;
  },
  length: function() {
    return this.dataStore.length;
  }
});

关于javascript - JS 实现栈时clear方法不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32427882/

相关文章:

c - goto后栈的状态

c++ - 为什么我使用 std::vector 创建堆栈的程序会崩溃?

javascript - 在一行中显示特定数量的元素并在屏幕尺寸缩小时使它们可滚动 - Flexbox

javascript - 禁用 Slick 网格中的特定单元格编辑

javascript - Jquery自动完成源php函数

c - 如何编写一个函数来获取任何节点类型的链表并释放它使用的内存?

algorithm - 是否有可能在分摊的次线性时间内计算一组数字的最小值模给定数字?

c - 跟踪插入队列的每个元素

javascript - 如何为 img setAttribute 设置后备图像

java - 将结构化文本/Lua 文档解析为字符串或表