限制数组大小

时间:2016-07-07 10:13:02

标签: javascript arrays

假设我有一个包含数据元素的数组,在此示例中为数字,如下所示:

var a = [432, 238, 122, 883, 983];

我想限制数组,所以每当我向数组添加一个元素时,它总是保持7或更小的长度,并删除最旧的元素。

我现在的aproach看起来像这样:

function add(x) {
    a.unshift(x);
    a = a.slice(0, 7);
}

它运作得很好,但是没有一种更优雅的方式来做,比如一条线或什么的?

编辑: 通过“更优雅”,我的意思是,我不需要添加功能,只需轻松内联我需要它的代码,而无需键入例如三次,只有一行也会使代码“更清晰” “

6 个答案:

答案 0 :(得分:12)

只是添加另一种可能的选择:

a = [x, ...a.slice(0, 6)];

即使我亲自选择Nina Scholzsolution(更改长度的“更好”条件以及不支持ES6的旧环境)

参考文献:

答案 1 :(得分:7)

按下后调整长度属性。

function add(x) {
    a.unshift(x);
    a.length = a.length < 7 ? a.length : 7;
}

清洁方式是在

之前检查
function add(x) {
    a.unshift(x);
    if (a.length > 7) {
        a.length = 7;
    }
}

答案 2 :(得分:3)

如果长度已经过去,你可以在添加和移动数组时检查数组的长度(删除第一个元素):

function add(x) {
    a.push(x);
    if (a.length > 7)
        a.shift();
}

答案 3 :(得分:0)

a=add(188);

function add(x){
  a.push(x);
  return a.slice(1);
}

答案 4 :(得分:0)

您也可以使用Array.pop。此外,如果您希望向数组添加属性,可以将其设置为通用。

&#13;
&#13;
Array.prototype.Limit_push = function(x) {
  this.unshift(x);
  if (this.maxLength !== undefined && this.length > this.maxLength) 
    this.pop();
}

var a = [];
a.maxLength = 7
for (var i = 0; i < 10; i++) {
  a.Limit_push(i);
  console.log(a)
}

var b = [];
for (var i = 0; i < 10; i++) {
  b.Limit_push(i);
  console.log(b)
}
&#13;
&#13;
&#13;

答案 5 :(得分:0)

如果需要,可以修改Array对象的原型。这样,所有数组都可以拥有自己的最大长度。

这很便宜且有效,但它可能无法与其他库和插件一起使用。

&#13;
&#13;
Array.prototype.maxLength = Number.MAX_VALUE;
Array.prototype.add = function(item) {
  this.push(item);
  this.adjustLength();
}
Array.prototype.adjustLength = function() {
  this.length = Math.min(this.length, this.maxLength);
}


var a = [432, 238, 122, 883, 983];
a.maxLength = 7;

a.add(1);
a.add(2);
a.add(3); // Ignored
a.add(4); // Ignored

document.body.innerHTML = '<ol start="0">'+a.map(function(i){return'<li>'+i+'</li>'}).join('')+'</ol>';
&#13;
ol li:before { content: '\0020\21d2\0020'; }
&#13;
&#13;
&#13;

如果您创建自己的类对象并委托给基础数组,则可以使其更具可移植性和可扩展性。

&#13;
&#13;
function MyList(arr, maxLength) {
  this.arr = arr || [];
  this.maxLength = maxLength || Number.MAX_VALUE;
}

MyList.prototype = {
  add : function(item) {
    this.arr.push(item);
    this.adjustLength();
  },
  adjustLength : function() {
    this.arr.length = Math.min(this.arr.length, this.maxLength);
  },
  get : function() {
    return this.arr;
  }
};

var a = new MyList([432, 238, 122, 883, 983], 7);

a.add(1);
a.add(2);
a.add(3); // Ignored
a.add(4); // Ignored

document.body.innerHTML = '<ol start="0">'+a.get().map(function(i){return'<li>'+i+'</li>'}).join('')+'</ol>';
&#13;
ol li:before { content: '\0020\21d2\0020'; }
&#13;
&#13;
&#13;