简体   繁体   English

为什么在此代码中计数已减少?

[英]Why in this code count has been decremented?

Why in this code count has been decremented first before deleting the last element of storage object? 为什么在删除存储对象的最后一个元素之前,先在此代码中先减少计数? In this way ,will it not delete the second last element instead of 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;
    }
  }
}

In (most) programming languages, arrays are zero-based. 在(大多数)编程语言中,数组是从零开始的。

So, for ['foo'] , count will be 1 , but 'foo' is at index 0 . 因此,对于['foo'] ,count将为1 ,但'foo'在索引0

So, the last element in an array will always be at index array.length - 1 . 因此,数组中的最后一个元素将始终位于索引array.length - 1


That said, if you make this.storage an array, the whole else block can be replaced. 也就是说,如果将this.storage为数组,则可以替换整个else块。

Since this.storage acts as an array any way, make it an array: 由于this.storage可以用作数组,因此请使其成为数组:

this.storage = [];

Then you can use: 然后,您可以使用:

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

Array.prototype.pop removes the last element from the array, and returns said element. Array.prototype.pop从数组中删除最后一个元素,并返回所述元素。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM