我正在创建我的堆栈类。我遵循了一本 javascript 数据结构书,但我更改了一些函数,但我不断收到一条错误消息,提示“s.length 不是函数”。我有一个长度函数,但我想知道因为在 javascript 中有一个关键字“length”然后与函数同名可能会导致问题。:
// 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());
最佳答案
首先,我不认为使用这种模式是个好主意:
function MyClass () {
this.method = method;
}
function method () {
// ...
}
它污染了命名空间,而 length
是一个常见的属性,它很快就会变得困惑。我更喜欢在定义构造函数后使用原型(prototype)对象的显式覆盖,这避免了对全局函数作为方法的需要。
也许这样的事情会更好? (为简洁起见省略注释)
function Stack()
{
this.dataStore = [];
// top of the stack
this.top = 0;
// this.push = push;
// this.pop = pop;
// this.peek = peek;
// this.length = length;
}
Stack.prototype.push = function(element)
{
this.dataStore.push(element);
}
Stack.prototype.pop = function()
{
return this.dataStore.pop( /*element*/ );
}
Stack.prototype.peek = function()
{
return this.dataStore[ /*items*/ this.dataStore.length-1];
}
Stack.prototype.length = function()
{
return this.dataStore.length;
}
Stack.prototype.clear = function()
{
return this.dataStore = [];
}
那么您的示例将起作用。
将length
作为用户定义的属性
快速测试,javascript 以这种方式覆盖 length
没有问题。这是因为 length
不是对象的属性(但是数组是),所以您可以在自己的类中自由地将它用作属性或方法名称。
关于javascript - 在 Javascript 中实现我的堆栈类时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498004/