我的 JavaScript 堆栈实现中的 Peek 方法未定义

Peek method in my JavaScript implementation of a stack is undefined

我实现了一个JS版本的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 方法。它 returns 未定义。我不知道为什么。

这就是我的使用方式。

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() {
    return this.stack[this.stack.length - 1]; 
};

this.length

的所有其他引用相同