JavaScript中MyQueue类属性变为undefined的报错求助
问题根源:构造函数拼写错误
你遇到的TypeError核心原因是**MyQueue类的构造函数拼写错误**:你写的是contructor(),正确的类构造函数名称应该是constructor()(少了一个字母c)。
在JavaScript中,类的构造函数必须严格使用constructor这个名称,拼写错误会导致该方法不会在实例化时自动执行,因此this.inputStack和this.outputStack始终是undefined,调用push方法时自然会触发“无法读取undefined的push属性”的错误。
修正后的完整代码
class MyQueue { // 修正构造函数拼写 constructor() { this.inputStack = new MyStack(); this.outputStack = new MyStack(); } push(val) { this.inputStack.push(val); } pop() { if(this.outputStack.empty()) { moveInputToOutput(this.inputStack, this.outputStack); // 栈是引用类型,直接操作后无需重新赋值 } return this.outputStack.pop(); } peek() { if(this.outputStack.empty()) { moveInputToOutput(this.inputStack, this.outputStack); } return this.outputStack.top(); } empty() { return this.inputStack.empty() && this.outputStack.empty(); } } // 优化:无需返回栈实例,直接操作引用即可 const moveInputToOutput = (inputStack, outputStack) => { while(!inputStack.empty()) { const inputvalue = inputStack.pop(); outputStack.push(inputvalue); } } class MyStack { constructor() { this.first = null; this.size = 0; } push(value) { const node = new Node(value); node.next = this.first; this.first = node; this.size++; } pop() { const node = this.first; this.first = this.first?.next ?? null; this.size = Math.max(0, this.size - 1); return node?.value; } empty() { return this.first === null; } top() { return this.first?.value; } } class Node { constructor(value){ this.value = value; this.next = null; } }
额外优化说明
- 移除不必要的返回值:
moveInputToOutput函数中,栈是引用类型,直接传入操作就会修改原实例,无需返回并重新赋值,简化了代码逻辑。 - 简化
pop方法逻辑:用空值合并运算符??替代冗余的三元表达式,用Math.max简化size更新逻辑,让代码更简洁。 - 精简
top方法:无需额外声明变量,直接返回目标值即可。
内容的提问来源于stack exchange,提问作者Fiore
相关产品推荐
相关产品推荐

