【问题标题】:Why in this code count has been decremented?为什么在此代码计数已减少?
【发布时间】:2017-10-06 13:00:22
【问题描述】:

为什么在删除存储对象的最后一个元素之前先减少此代码计数? 这样会不会删除倒数第二个元素而不是last?

var stack = function () {
  this.count = 0;
  this.storage = {};
  this.push = function (value) {
    this.storage[this.count] = value;
    this.count++;
  }
  this.pop = function () {
    if (this.count === 0) {
      return undefined;
    }
    else {
      this.count--;
      var result = this.storage[this.count];
      delete this.storage[this.count];
      return result;
    }
  }
}

【问题讨论】:

    标签: javascript data-structures stack


    【解决方案1】:

    在(大多数)编程语言中,数组是从零开始的。

    因此,对于['foo'],计数将为1,但'foo' 位于索引0

    因此,数组中的最后一个元素将始终位于索引array.length - 1


    也就是说,如果将this.storage 设为数组,则可以替换整个else 块。

    由于this.storage 以任何方式充当数组,因此将其设为数组:

    this.storage = [];
    

    那么你可以使用:

    else {
      this.count--;
      return this.storage.pop();
    }
    

    Array.prototype.pop 从数组中移除最后一个元素,并返回该元素。

    【讨论】:

      【解决方案2】:

      Count 等于数据结构中第一个空闲位置的索引,然后在当前 count 之后进行加法,然后通过对称减少 before 指向最后一个被释放的元素,因此 count指向最后释放的位置。

      【讨论】:

        【解决方案3】:

        因为数组是 0 索引的,所以第一个元素存储在第 0 个索引处,第 2 个存储在第 1 个索引处,依此类推

        【讨论】:

        • 所以,这就是为什么将 count 初始化为零以便抵消这种影响。
        猜你喜欢
        • 1970-01-01
        • 2012-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        • 2012-12-09
        • 1970-01-01
        相关资源
        最近更新 更多