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?
我需要在Javascript数组中只维护特定数量的元素。让我们说数组中只有10个项目。它应该遵循FIFO概念,这意味着如果阵列上有10个项目并且添加了新项目,那么项目[0]应该自动弹出数组。有没有办法做到这一点,还是我应该在Javascript数组上以编程方式完成整个过程?
1 个解决方案
#1
2
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);
}
#1
2
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);
}