Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
堆栈的JavaScript实现中的Peek方法未定义_Javascript_Data Structures_Stack - Fatal编程技术网

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

堆栈的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[

我已经用JS实现了一个版本的堆栈数据结构

这是我的密码

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