Limit array size

前端 未结 6 1782
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 05:25

Let\'s say I have an array with data elements, in this example numbers, like this:

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

And I want to limit t

6条回答
  •  臣服心动
    2021-01-04 05:51

    You can also use Array.pop. Also if you wish to add a property to array, you can make it generic.

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

提交回复
热议问题