【发布时间】: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