我有一个由整数ID定义的JS对象列表。获取尚未在Javascript中使用的较低整数ID
objects = [{
id: 0,
type: 'null'
}, {
id: 1,
type: 'foo'
}, {
id: 2,
type: 'bar'
}];
我实现了一个功能,从我的列表中删除一个元素:
removeObject = function(o){
objects.splice(objects.indexOf(o), 1);
}
我的问题是,我需要建立一个功能到我的列表中添加新项与ID尚未使用(例如列表中不存在的较低正整数)。
我试图做这样的事情,但当我删除对象0(例如)它不起作用。
我该怎么做?
编辑1
根据您的回答,我认为在性能方面最好的解决方法就是使用topId,当我在我的列表中添加一个新的对象,总是递增。
但这并不能满足我的要求。其实我认为@X-Pippes的反应可能会很好。
我应该做些事情那样:
objects = [{
id: 0,
type: 'null'
}, {
id: 1,
type: 'foo'
}, {
id: 2,
type: 'bar'
}];
// Init available ids list with the default value
availableIds = [objects.length];
removeObject = function(o){
// Remove the object from the list
objects.splice(objects.indexOf(o), 1);
// Add its id to the available ids list
availableIds.push(o.id);
}
addObject = function(type){
// Get lower id available
var newId = Math.min.apply(Math,availableIds);
// Push the new object with the id retrieved
objects.push({
id: newId,
type: type
});
// Remove used id from the available ids list
availableIds.splice(availableIds.indexOf(newId), 1);
// Add a default id if available list is empty
if(availableIds.length < 1) availableIds.push(objects.length);
};
如果您删除实例0,则下一个addObject应与id = 0? –
为什么不简单地跟踪上次使用的ID并增量?为什么使用数组而不是地图? –
正在使用数组并跟踪移动索引时删除项目,而不是每个项目的id,而不是问题?对于最好的解决方案,数组,散列表等,它将取决于项目从列表中被逐出的频率以及您需要的其他操作。 –