使用构造函数函数添加和删除项的数据结构

Data structure adding and removing items using constructor functions

本文关键字:删除 数据结构 添加 构造函数 函数      更新时间:2023-09-26

这是一个数据结构练习的开始,我正在尝试编写一个添加和删除函数——它应该很简单,我不明白为什么它错了?!此外,使用构造函数、原型等的方法(必须保持原样)非常感谢您的帮助!

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

您的minus函数没有返回语句,因此它只返回默认情况下未定义的

您可以像在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;
};