【发布时间】: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