Here's my data stru开发者_如何学JAVActure:
var data = [
{ id: '1924', info: 'boo' },
{ id: '1967', info: 'foo' }
];
The id value should be unique, but the info may not be unique. How would I add new data into the data hash only if the id of the new data is unique?
Is the only way to iterate over the whole hash and see if there is such an id already in place?
data.push({ id: '1967', info: 'goo-goo' }); //should not be added
data.push({ id: '1963', info: 'goo-goo' }); //should be added
If you can change your data structure, it can be done with less code:
var data = {
'1924': {'info': 'goo-goo'},
'1967': {'info': 'boo-boo'}
};
function add(obj, id, data) {
if (obj[id] === undefined) { // if you have fear about the prototype chain being poisoned
// add in a hasOwnProperty
obj[id] = data;
}
}
This will also have the benefit of being a lot faster to access (if you have the ID).
Ivo, the problem with your solution is that I also keep track of the index of the info currently being displayed. The index of { id: '1967', info: 'foo' }
would be 1 in that data hash, so I can reference it by data[1]
if needed.
精彩评论