gpt4 book ai didi

javascript - 在数组中保留某些 n 个新鲜值的最佳方法

转载 作者:行者123 更新时间:2023-12-03 01:42:33 25 4
gpt4 key购买 nike

我有一个内部有 4 个数组的对象,如下所示:

let obj = {
A: [1,2,5,8,10,15,20],
B: [5,1,5,8,10,18,5],
C: [1,2,2,8,1,15,4],
D: [1,2,1,8,8,1,3],
}

这些数组是实时填充的,因此每次新值到达时,它都会被推送到这些数组中。所有 4 个数组的长度都相同。

但我必须只维护最后 50 个值,所以我这样做:

if (obj.A.length > 50) {
obj.A.shift()
obj.B.shift()
obj.C.shift()
obj.D.shift()
}

是否有更好的方法来达到与上面相同的结果?

最佳答案

也许有一个选项可以让您对希望在 Array 对象上实现的方法进行原型(prototype)设计,从而限制数组中的对象数量。

选项 1

在下一个示例中,您不需要每次都检查第一个数组的长度,然后假设其他数组的长度,并且每个数组都保留其自己的状态。

Array.prototype.pushMax = function(max, value) {
if (this.length >= max) {
this.splice(0, this.length - max + 1);
}
return this.push(value);
};
const max = 3;
const arr = [];
arr.pushMax(max, 1);
arr.pushMax(max, 2);
arr.pushMax(max, 3);
arr.pushMax(max, 4);
arr.pushMax(max, 5);
console.log(arr);

选项 2

如果您想在数组的开头获得最新值,您可以执行类似的操作:

Array.prototype.pushStartMax = function(max, value) {
if (this.length >= max) {
this.pop();
}
return this.unshift(value);
};
const max = 3;
const a = [];
a.pushStartMax(max, 1);
a.pushStartMax(max, 2);
a.pushStartMax(max, 3);
a.pushStartMax(max, 4);

console.log(a);

关于javascript - 在数组中保留某些 n 个新鲜值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50768279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com