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
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'- '+i+'
'}).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'- '+i+'
'}).join('')+'
';
ol li:before { content: '\0020\21d2\0020'; }