javascript - 如何使用自定义方法取消移位/移位单个值和多个值?

标签 javascript arrays prototype

我有原型(prototype)来重新创建数组方法的工作原理,pop/push/shift/等,我想扩展功能以执行以下操作:

  1. 推送/弹出/移位/取消移位多个值 array.push(0); array.push(1); array.push(2); 期望(array.pop()).to.be(2); 期望(array.pop()).to.be(1); 期望(array.pop()).to.be(0);

  2. Push/Pop/unshift/etc 单个值 array.push(0); array.push(1); 期待([0,1]); 数组.pop(1); 期待([0]);

我的假设是我需要一个全局数组变量来存储元素。是这样吗?

这是我的代码:

var mainArray = [];  // array no longer destroyed after fn() runs
function YourArray(value) {
  this.arr = mainArray;  // looks to global for elements | function?
  this.index = 0;
  var l = mainArray.length;

  if(this.arr === 'undefined')
    mainArray += value;        //  add value if array is empty
  else
    for(var i = 0; i < l ; i++)             // check array length
        mainArray += mainArray[i] = value;  // create array index & val

  return this.arr;
}

YourArray.prototype.push = function( value ) {
  this.arr[ this.index++ ] = value;
  return this;
};

YourArray.prototype.pop = function( value ) {
  this.arr[ this.index-- ] = value;
  return this;
};

var arr = new YourArray();
arr.push(2);
console.log(mainArray); 

最佳答案

My assumption is that I would need a global array variable to store the elements. Is that the right?

没有。这是不对的。

您希望每个数组对象都有自己独立的数据集。否则,你的程序中怎么会有多个数组?

function YourArray(value) {
  this.arr = [];  // This is the data belonging to this instance. 
  this.index = 0;
  if(typeof(value) != 'undefined')) {
    this.arr = [value];
    this.index = 1;
  }
}

////////////////////////////////////
// Add prototype methods here
///////////////////////////////////

var array1 = new YourArray();
var array2 = new YourArray();
array1.push(2);
array1.push(4);
array2.push(3);
array2.push(9);
// Demonstrate that the values of one array
// are unaffected by the values of a different array
expect(array1.pop()).to.be(4);
expect(array2.pop()).to.be(9);

关于javascript - 如何使用自定义方法取消移位/移位单个值和多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33644232/

相关文章:

javascript - 使用 documentFragment 的 IE 性能不佳

javascript - 原型(prototype)继承返回值

javascript - 使用映射和过滤器扩展语法

python - 将数组四舍五入为另一个数组中给定的值

javascript - JavaScript 的原生原型(prototype)何时在同源框架之间共享?

javascript - 当使用 apply() 和 call() 方法很容易继承时,为什么人们在 JavaScript 中使用原型(prototype)?

javascript - 在 Jive 中调整 HTML 小部件的大小

javascript - 强制导向的超链接不起作用

JavaScript - 按两个整数属性对数组进行排序

python - 将文本转换为 numpy 数组