简体   繁体   English

如何在Javascript数组中仅维护特定数量的元素

[英]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. 我需要在Javascript数组中只维护特定数量的元素。 Lets say only 10 items in the array. 让我们说数组中只有10个项目。 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. 它应该遵循FIFO概念,这意味着如果阵列上有10个项目并且添加了新项目,那么项目[0]应该自动弹出数组。 Is there a way to do this or should I be doing the whole stuff programatically on Javascript array? 有没有办法做到这一点,还是我应该在Javascript数组上以编程方式完成整个过程?

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/ http://jsfiddle.net/6Nevz/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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