【问题标题】:javascript typeError: cannot read property of undefinedjavascript typeError:无法读取未定义的属性
【发布时间】:2017-06-29 09:27:50
【问题描述】:

我正在尝试在 Javascript 中创建一个堆栈类,但我不断收到上述错误的变体。我知道它是构造函数,但我就是找不到问题所在。这是我的课:

"use strict"

class Stack {
    constuctor() {
        this.items = [];
    }

    emptyArray() {
        if (this.items === 0) {
            this.error = "The stack is empty";
        }
        return this.error;
    }

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

    push(x) {
        return this.items.push(x);
    }

    pop() {
        if (this.items >= 1) {
            return this.items.pop();
        }
        else {
            throw new emptyArray();
        }
    }

    size() {
        return this.items.length;
    }

    peak() {
        let el1 = this.items.pop();
        let el2 = this.items.pop();
        this.items.push(el2);
        this.items.push(el1);
        return el2;
    }
}

new Stack().size();

【问题讨论】:

  • 例如,如果我尝试 stack.push(x),我会得到“无法读取属性推送”,或者如果我使用 stack.size(),我会得到“无法读取属性”长度”等。
  • 你确定你的变量已经定义了吗?尝试使用alert() 来查看它是否已定义。
  • 要查看数组是否为空,请不要使用this.items === 0。使用这个this.items.length === 0!比较长度而不是数组本身!
  • 你说得对,我太傻了

标签: javascript class typeerror


【解决方案1】:

constructor 拼写错误:

constuctor() {
    this.items = [];
}

【讨论】:

  • 每个人都会遇到这种情况:)
猜你喜欢
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多