Here is what I need:
var user = {
'White' : 24,
'Jack' : 25,
'Jone' : 24,
……
}
In this obj, I want to store name and age of a person. And the obj can only store 10 person. If the 11th person is added, the first person should be delete. So I'm thinking of an array, the unshift and pop method:
var user = [
{'White': 24},
{'Jack' : 25},
{'Jone' : 24},
……
]
user.unshif({'Bob': 24});
if(user.length>10){user.pop()};
This works fine except one problem. When I want to know White's age, I must use a loop:
for(var i=0; i<user.length; i++){
……
}
I don't think it's a good method. is there any array-like object that can meet the needs. And here is what I do:
function arrayObj(){
var arr = [], obj = {};
this.pop = function(){
var o = arr.pop();
if(o){
for(var k in o){ delete obj[k]; }
this.length--;
}
};
this.unshift = function(o){
arr.unshift(o);
for(var k in o){ obj[k] = o[k]; }
this.length++;
};
this.length = 0;
this.get = function(n){
if(obj[n]!=null && obj[n]!=undefined){
return obj[n];
} else {
return null;
}
};
}
var user = new arrayObj();