简体   繁体   中英

Push to an array and keep the array n items long

How do I push an object to an array, then when the array becomes, say, 100 items in size, remove the first one and push again, and so on?

It could be a method, like arr.push('log item', 100) How do I implement it better?

You might be looking for something like this:

if(arr.length === 100)
        arr.shift(); 
arr.push(VAL);

A method more like the OP's original request, replacing the push() with a new one with the option of limiting the size of the array

Array.prototype.originalPush = Array.prototype.push;
Array.prototype.push = function(val,limit)
{
    if(limit && this.length == limit)
        this.shift();
    this.originalPush(val);
}

You can simpy shift when you go over fixed length:

 Array.prototype.push_maxlength = function(item, length) { this.push(item); if (this.length > length) { this.shift(); } } var a = [1, 2, 3]; for (var i = 0; i < 10; ++i) { a.push_maxlength(i, 5); console.log(JSON.stringify(a)); } 

myArray.slice(1) will return an array without the first item. So something along the lines of :

myArray.push(myNewData);
if (myArray.length > 100) {
  myArray = myArray.slice(1);
}

Check length!

function addTo100(array, newItem){
    if (array.length == 100){
        array.shift();
    }
    array.push(newItem);
    return array;
}
function pushMax(arr, val, maxLength) {
    arr.push(val);

    if (arr.length > maxLength) {
        array.shift();
    }
}

pushMax(arr, 'log item', 100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM