我最近在看这本书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 值。谁能解释一下发生了什么事吗?谢谢!
最佳答案
It seems like setting the top to 0 only changes the pointer and the
dataStore
is unchanged, meaning that further operations would just overwrite the previousdataStore
values.
你说得完全正确。我同意这种行为可能是不可取的。
相反,我建议如下:
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;
}
});
关于javascript - JS 实现栈时clear方法不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32427882/