如何强制数组拥有特定数量的元素?

Javascript - How can i force an array to have a specific amount of elements

本文关键字:元素 何强制 数组 拥有      更新时间:2023-09-26

是否有一种简单的方法使数组具有特定数量的元素?从某种意义上说,如果您将更多的元素放入其中,它将覆盖第一个元素。

例如,我想要一个只包含2个元素的数组。如果我推入第三个元素,它应该覆盖最早的元素(in的第一个)。像一个堆栈。

您可以使用计数器并使用所需长度的模进行插入。

function push(array, length) {
    var counter = 0;
    return function (value) {
        array[counter % length] = value;
        counter++;
    };
}
var array = [],
    pushToArray = push(array, 2);
pushToArray(1);
console.log(array);
pushToArray(2);
console.log(array);
pushToArray(3);
console.log(array);
pushToArray(4)
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

所以正如我上面评论的那样,你可以通过数组子类化来做到这一点。下面的代码片段介绍了一个新的Array结构,它有两个新方法:lastpush。然而,我们的新push掩盖了Array.prototype的实际push方法。新的push将第一个参数作为数组长度的限制,例如[1,2,3].push(4,"a","b","c")将长度限制为4,结果将是[3,"a","b","c"]。返回值将是数组中被删除的元素,因为我们在底层使用splice

function SubArray(...a) {
  Object.setPrototypeOf(a, SubArray.prototype);
  return a;
}
SubArray.prototype = Object.create(Array.prototype);
SubArray.prototype.last = function() {
  return this[this.length - 1];
};
SubArray.prototype.push = function(lim,...a){
  Array.prototype.push.apply(this,a);
  return this.splice(0,this.length-lim);
};
myArray = new SubArray(1,2,3);
myArray.last();
myArray.push(4,"a","b","c");
console.log(myArray);