JS实现栈时clear方法不清楚

Clear method is unclear when implementing stacks in JS

我最近在看这本书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 值。任何人都可以解释发生了什么事吗?谢谢!

没有清除数据存储,因为没有必要。当您使用此堆栈对象时,您不需要直接使用 dataStore,只需通过 Stack 对象的函数即可。

所以你可以保持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;
  }
});