这是数据结构练习的开始,我正在尝试编写一个添加和删除函数 - 它应该如此简单,但我不明白为什么它是错误的?!另外,8使用构造函数、原型(prototype)等的方法必须保持原样) 非常感谢任何帮助!
function Thestack () {
this.array=[];
}
Thestack.prototype.plus = function (i) {
this.array.push(i);
return this; // cannot be edited
};
Thestack.prototype.minus = function () {
this.array.pop();
};
var smallstack = new Thetack();
smallstack.plus(something); //followed by
smallstack.minus();
should return: something
最佳答案
您的减号函数没有 return 语句,因此默认情况下它只是返回 undefined
您可以在 add
函数中返回 this
,这样您就可以继续链接方法、返回删除的元素或返回剩余数组的长度
// return this for chaining
Thestack.prototype.minus = function () {
this.data.pop();
return this;
};
// return the removed item
Thestack.prototype.minus = function () {
//edits the data array in place and returns the last element
return this.data.pop();
};
// return the length of the remaining array
Thestack.prototype.minus = function () {
this.data.pop();
return this.data.length;
};
关于javascript - 使用构造函数添加和删除项目的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38449932/