[英]How to remove element from 2d array
I have a 2d array like this: 我有一个像这样的二维数组:
var rawData = [
[1325347200000, 60], [1328025600000, 100], [1330531200000, 15], [1333209600000, 50]
];
//MEMORY
mem.push([
iteration,
memory.usage / (1024*1024)
]);
that keeps growing. 保持增长。 I want to limit the size to 20, so I want to remove the oldest element in the array.
我想将大小限制为20,所以我想删除数组中最旧的元素。 I tried this but remove one element but keeps growing
我试过了,但是删除了一个元素,但是一直在增长
//Remove first
if(iteration % 20 === 0) {
rawData = rawData.splice(1);
}
I would implement an own push method that leftshifts the whole array: 我将实现自己的push方法,该方法会将整个数组左移:
class LimitedArray extends Array {
constructor(max, ...args){
super(max);
this.push(...args);
}
push(...els){
for(let i = els.length; i < this.length; i++)
this[i - els.length] = this[i];
for(let i = 0; i < els.length; i++)
this[i + this.length - els.length] = els[i];
}
}
So one can do: 所以可以做到:
const cache = new LimitedArray(20);
cache.push(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
cache.push(22);
If you really want to do that "inline", you can do: 如果您确实想进行“内联”,则可以执行以下操作:
mem.push([1,2]);
if(mem.length > 20) mem.shift();
Or if its not accurate and mem might be longer than 21: 或者,如果它不准确并且mem可能长于21:
mem.push([1,2],[3,4]);
if(mem.length > 20) mem.splice(0, mem.length - 20);
As suggested in the comments already, that can be simplified to: 正如评论中已经建议的那样,可以简化为:
mem.push([1,2], [3,4]);
mem = mem.slice(-20);
however that might be less performant and less memory efficient. 但是,这可能会降低性能,降低内存效率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.