我正在使用javascript学习数据结构/算法,但无法找出堆栈中的错误。代码是:
//first javascript algo
console.log("program working");
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peak = peak;
function push(element) {
this.datastore[this.top++] = element;
}
function pop(element) {
return this.datastore[--this.top];
}
function peak() {
return this.datastore[this.top - 1];
}
}
var FirstStack = new Stack();
FirstStack.push(1);
FirstStack.push(2);
FirstStack.push(3);
console.log("Peak:" + FirstStack.peak());
console.log("Pop:" + FirstStack.pop());
console.log("Pop:" + FirstStack.pop());
我得到的错误是
" this.datastore[this.top++] = element;
^
TypeError: Cannot set property '0' of undefined
at Stack.push (/Users/mg8686./Desktop/javascriptalgos/algo1.js:13:32)
at Object.<anonymous> (/Users/mg8686./Desktop/javascriptalgos/algo1.js:26:12)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
有人可以让我知道我做错了吗?谢谢!!
问题出在外壳上。
您已定义:
this.dataStore = [];
并尝试访问
this.datastore
Javascript区分大小写。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句