2017-10-06 79 views
0

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

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

回答

0

计数的第二等于第一空闲位置的索引数据结构,然后添加发生在当前计数增加后,并通过对称减少之前指向释放的最后一个元素,因此计数指向最后一个释放位置的点。

2

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

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

因此,在阵列中的最后一个元素将总是位于索引array.length - 1


这就是说,如果你让this.storage一个数组,整个else块可更换。

由于this.storage充当阵列的任何方式,使其成为一个数组:

this.storage = []; 

然后你可以使用:

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

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

0

因为该阵列被0索引,所述第一元件被存储在第0索引处,在第1'索引等

+0

所以,这就是为什么count已经初始化为零,以便它可以抵消这种影响。 –