【发布时间】:2017-01-06 02:28:46
【问题描述】:
我正在创建我的堆栈类。我遵循了一本 javascript 数据结构书,但我更改了一些函数,但我不断收到一条错误消息,上面写着“s.length 不是函数”。我有一个长度函数,但我想知道既然 javascript 中有一个关键字“长度”,那么与函数同名可能会导致问题。:
// LIFO
function Stack()
{
this.dataStore = [];
// top of the stack
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
}
function push(element)
{
// when new element is pushed, it needs to be stored
// in the top position and top var needs to be incremented
// so the new top is the next empty pos in the array
//this.dataStore(this.top++) = element;
// the increment op after the call ensures that the
// current value of top is used to place the new element
// at the top of the stack before top is incremented
this.dataStore.push(element);
}
function pop()
{
// returns element in top pos of stack and then decrements
// the top variable
//return this.dataStore[--this.top];
return this.dataStore.pop(element);
}
function peek()
{
// returns the top element of the stack by accessing
// the element at the top-1 position of the array
//return this.dataStore[this.top-1];
return this.dataStore[items.length-1];
}
function length()
{
//return this.top;
return this.dataStore.length;
}
function clear()
{
//return this.top = 0;
return this.dataStore = [];
}
var s = new Stack();
s.push("David");
s.push("Raymond");
s.push("Bryan");
console.log("length: " + s.length());
【问题讨论】:
标签: javascript algorithm data-structures stack