【问题标题】:Javascript - How can i force an array to have a specific amount of elementsJavascript - 我如何强制数组具有特定数量的元素
【发布时间】:2017-03-31 16:12:51
【问题描述】:

有没有一种简单的方法可以使数组具有特定数量的元素。 从某种意义上说,如果你投入更多,它就会覆盖第一个元素。

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

【问题讨论】:

  • 虽然有可能,但不建议这样做。使用您自己的数据结构(在内部使用数组)来完成此操作要明智得多。
  • 看到这个stackoverflow.com/questions/7727919/creating-a-fixed-size-stack
    在javascript中做类似的事情
  • 堆栈会移除第一个元素并推到顶部。
  • 您将不得不使用 Array 子类化来创建一个新数组,该数组在其原型中具有自己的 push 方法,以抑制/隐藏 Array.prototype 的 push 方法。一旦长度达到某个值,它自己的 push 方法应该负责将索引 0 处的项目移出操作。

标签: javascript arrays stack


【解决方案1】:

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

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; }

【讨论】:

    【解决方案2】:

    正如我在上面评论的那样,您可以通过数组子类化来做到这一点。下面的 sn-p 引入了一个新的 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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-29
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多