简体   繁体   中英

How to maintain only a specific number of elements in a Javascript Array

I require to maintain only a specific number of elements in an Javascript array. Lets say only 10 items in the array. It should follow the FIFO concept, which means if there are 10 items on the array and a new item is added, then the item[0] should automatically be popped out of the array. Is there a way to do this or should I be doing the whole stuff programatically on Javascript array?

I'd probably create my own object that has an array in it:

var myArray = {
    arr: [],
    add: function(val) {
        this.arr.unshift(val);
        if (this.arr.length > 10) {
            this.arr.length = 10;
        }
    }
};

for (var i = 0; i < 15; i++) {
    myArray.add(i);
    //alert(myArray.arr.length);
}​

http://jsfiddle.net/6Nevz/2/

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