堆栈的JavaScript实现中的Peek方法未定义
我已经用JS实现了一个版本的堆栈数据结构 这是我的密码堆栈的JavaScript实现中的Peek方法未定义,javascript,data-structures,stack,Javascript,Data Structures,Stack,我已经用JS实现了一个版本的堆栈数据结构 这是我的密码 class Stack { constructor() { this.stack = []; }; push(item) { return this.stack.push(item); }; pop() { return this.stack.pop(); }; peek() { return this.stack[
class Stack {
constructor() {
this.stack = [];
};
push(item) {
return this.stack.push(item);
};
pop() {
return this.stack.pop();
};
peek() {
return this.stack[this.length - 1];
};
isEmpty() {
return this.length === 0;
};
getLength() {
return this.stack.length;
};
}
除了peek方法,这里的一切都很好。它返回undefined。我不知道为什么
这就是我使用它的方式
const stack = new Stack();
console.log(` The stack contains : ${stack.getLength()} items`);
stack.push(1);
stack.push(2);
console.log(`The stack contains : ${stack.getLength()} items`);
console.log(stack.peek());
这是输出
The stack contains : 0 items
The stack contains : 2 items
undefined
您需要使用
this.stack.length
而不是this.length
:
peek(){
返回this.stack[this.stack.length-1];
};
对
this.length
this.stack.length
的所有其他引用相同,而不是this.length