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

时间:2016-07-19 05:04:25

标签: javascript arrays data-structures push

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

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

1 个答案:

答案 0 :(得分:1)

你的减号函数没有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;
};