【问题标题】:How to create an array with a maximum size?如何创建具有最大大小的数组?
【发布时间】:2015-11-18 22:23:50
【问题描述】:

我想创建一个不会超过 5 个元素的 javascript 数组,并将所有溢出的元素作为队列删除。到目前为止,我最好的想法是覆盖数组 push 方法并检查数组的当前长度是否超过 5,如果是,则在添加元素后,执行 array.splice(0,1) 以删除最后一个元素。这是正确的做法吗?

【问题讨论】:

  • shift() 可能比splice(0,1) 性能更高,但您的算法似乎很可靠。
  • 我会说创建自己的具有 5 个元素限制的数组构造函数。

标签: javascript arrays queue


【解决方案1】:

这样的东西可以吗?

var myArr = [];

function arrayPusher(data) {

  //Add the data to the front of the array.
  myArr.unshift(data);

  //After adding the element to the array,
  //if it is too long, remove the last item.
  if (myArr.length > 5) {
    myArr.pop();
  }
}

【讨论】:

    【解决方案2】:

    我看不到您无法控制数组的情况,但将array.length = 5; 放入您的长度检查功能要简单得多。这将一次性删除第 5 个元素之后的任何内容。

    【讨论】:

      【解决方案3】:

      嗯,我认为最好的办法是创建一个循环,重新使用您的函数,如下所示:

      function onlyN_Elements(N,vector){
         if(vector.length<=N){
             return vector;
         }else{
             vector.pop();
             onlyN_Elements(N,vector);
         } 
      } 
      

      因此,您总是想执行此操作,只需执行此操作:

      a = [ 2, 3, 4, 5, 6, 7, 8];  //vector
      N = 5                        //number of maximun length vector
      onlyN_Elements(N,a);         // just execute the function
      
      --> output --> console.log(a) --> a = [ 2, 3, 4, 5, 6 ]
      

      因此,如果您想更改矢量的最大长度,只需更改“N”即可。 ;)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 2019-02-27
        • 1970-01-01
        相关资源
        最近更新 更多