gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:28:54 25 4
gpt4 key购买 nike

我有原型(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com