【问题标题】:Clear method is unclear when implementing stacks in JSJS中实现栈时clear方法不清楚
【发布时间】:2015-09-06 20:18:39
【问题描述】:

我最近在看这本书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 值。谁能解释发生了什么?谢谢!

【问题讨论】:

  • 它只是从 0 开始覆盖。不清除数组中的元素。
  • 这些函数都应该是Stack原型上的方法。您在此处显示的此代码将不起作用。
  • 是的,我只是复制并粘贴了书中的代码。我认为这个示例代码是出于演示目的或其他目的。

标签: javascript data-structures stack


【解决方案1】:

似乎将顶部设置为 0 只会更改指针和 dataStore 没有改变,这意味着进一步的操作将只是 覆盖之前的 dataStore 值。

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

相反,我建议如下:

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;
  }
});

【讨论】:

    【解决方案2】:

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

    所以你可以保持dataStore不变,它允许你用更少的操作完成同样的工作,也许更快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      相关资源
      最近更新 更多