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

标签 javascript arrays data-structures push

这是数据结构练习的开始,我正在尝试编写一个添加和删除函数 - 它应该如此简单,但我不明白为什么它是错误的?!另外,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/

相关文章:

javascript - 为什么我的计时器不增加数字?

arrays - Ajax DATA 更​​改排序

c++ - 将数组大小减少到 1 的最小成本

c++ - std::map 上的 make_heap 具有用户定义的比较和随机访问迭代器

javascript - 为什么有些网站使用 GET 参数访问特定版本的 CSS 或 JavaScript 文件?

javascript - 防止 Ctrl S 上出现“保存”对话框

javascript - 我的网站如何让访问者登录到第三方网站?

python - 基于 2D numpy 索引数组排列 numpy 2D 数组的 numpy 方式是什么?

javascript - 为什么这个匿名函数在 Javascript 中返回 undefined ?

c++ - 二叉树中的节点搜索溢出堆栈