Limit array size

前端 未结 6 1823
隐瞒了意图╮
隐瞒了意图╮ 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 06:03

    If you want, you can modify the prototype of the Array object. This way all of your arrays can have their own max length.

    This is cheap and effective, but it may not work well with other libraries and plugins.

    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 = '
      '+a.map(function(i){return'
    1. '+i+'
    2. '}).join('')+'
    ';
    ol li:before { content: '\0020\21d2\0020'; }

    If you create your own class object and delegate to an underlying array, you can make this more portable and extensible.

    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 = '
      '+a.get().map(function(i){return'
    1. '+i+'
    2. '}).join('')+'
    ';
    ol li:before { content: '\0020\21d2\0020'; }

提交回复
热议问题