我有一個由整數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,而不是問題?對於最好的解決方案,數組,散列表等,它將取決於項目從列表中被逐出的頻率以及您需要的其他操作。 –