You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现链式栈pop/peek/toString返回undefined问题咨询

问题解答

这个故障不是作用域问题,是方法逻辑分支缺失、边界处理不完善导致的,具体问题和修复方案如下:

存在的问题

  • peek()、pop()方法空栈处理逻辑不完整:判断栈为空时仅打印提示,没有提前返回阻断后续代码,空栈调用时会尝试读取null.data直接抛出类型错误,无法正常返回结果。
  • toString()方法返回逻辑覆盖不全:仅在栈长度大于1时才会返回拼接完成的字符串,栈长度为0或1时没有显式返回值,会默认返回undefined;同时长度为0/1时没有补全字符串末尾的],输出格式不符合预期。
  • 额外优化点:当前类方法全部写成箭头函数形式的实例属性,每创建一个栈实例都会单独生成一套方法副本,存在不必要的内存开销,建议写成原型上的普通类方法。

修复后完整代码

class Node {
    /* 创建带数据和后继指针的节点 */
    constructor(e, n) {
        this.data = e;
        this.next = n;
    }
}

class LinkedStack {
    /* 初始化空栈 */
    constructor() {
        this.top = null;
        this.size = 0;
    }

    push(elem) {
        let v = new Node(elem, this.top);
        this.top = v;
        this.size++;
    }

    length() {
        return this.size;
    }

    isEmpty() {
        return this.size === 0;
    }

    peek() {
        if (this.isEmpty()) {
            console.log("Empty Stack");
            return null;
        }
        return this.top.data;
    }

    pop() {
        if (this.isEmpty()) {
            console.log("Empty Stack");
            return null;
        }
        const temp = this.top.data;
        this.top = this.top.next;
        this.size--;
        return temp;
    }

    toString() {
        let s = "[";
        let cur = this.top;
        // 直接遍历链表节点,无需依赖长度计数,逻辑更简洁不易出错
        while (cur !== null) {
            s += cur.data;
            if (cur.next !== null) {
                s += ", ";
            }
            cur = cur.next;
        }
        s += "]";
        return s;
    }
}

// 测试用例
let stack = new LinkedStack();
stack.push(9);
console.log(stack.pop() + " was popped"); // 输出:9 was popped
stack.push(12);
stack.push(15);
console.log("Is Stack Empty? " + stack.isEmpty()); // 输出:Is Stack Empty? false
console.log("Stack Length: " + stack.length()); // 输出:Stack Length: 2
console.log("Top value: " + stack.peek()); // 输出:Top value: 15
console.log("Stack Content: " + stack.toString()); // 输出:Stack Content: [15, 12]

内容的提问来源于stack exchange,提问作者rojey12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 09:27:31