确定“最旧”的唯一可靠方法是保留某种索引,可能使用数组。每当您更新对象时,您都会检查该属性是否存在或不使用propertyName in Object
. 如果是,则从数组中拼接它并使用 unshift 将它放在索引 0 处,然后在对象上更新它的值。
如果它不存在,并且数组长度等于最大属性计数,pop
则数组中最旧的属性名称,unshift
索引为 0 的新属性,delete
对象中的旧属性并添加新属性。
如果它不存在并且数组长度小于最大属性计数,unshift
则将数组上的名称添加到索引 0 并将其添加到对象中。
编辑
一些代码。请注意,您需要防止覆盖 *_maxPropCount* 和 *_index* 属性,我将把它留给您。
var o = {a:1, b:2, _maxPropCount: 2, _index: ['a','b']};
function updateObject(obj, prop, value) {
var idx = obj._index;
var i, lastProp;
// If property exists, move to start of index array
if (prop in obj) {
i = idx.indexOf(prop);
idx.unshift(idx.splice(i, 1));
// Otherwise, property doesn't exist so check length and
// number of properties
} else {
// If already have full count, pop last property name from end of array
// and delete from object
if (idx.length == o._maxPropCount) {
lastProp = idx.pop();
delete o[lastProp];
}
// Update index
idx.unshift(prop);
}
// Update object
obj[prop] = value;
}
updateObject(o, 'b', 6);
alert(o._index + ' ' + o.b); // b,a 6
updateObject(o, 'g', 2);
alert(o._index + ' ' + o.a); // g,b undefined
代码可能会缩短几行,但这不会使其更快。哦,而且indexOf是 ES5,所以在旧浏览器上不可用,需要一个 shim,如果你有很多属性,这对于需要使用它的 UA 来说会很慢。