我需要一个数据结构来存储多个JavaScript对象,并且能够使用字符串id(get / set / delete操作)访问它们。
以下是我需要存储的项目示例:
var Player = function(name) {
this.name = name;
this.x = 0;
this.y = 0;
this.toString = function() {
return 'player : ' + this.name + ' at ' + this.x + ', ' + this.y;
};
}
我想将玩家存储在一个数据结构中,并且能够通过他们的名字来获取/设置/删除它们,例如players.get('Bob')
以获得名为Bob的玩家。
起初,我以为我可以使用名称为关键的地图(我正在使用来自collectionsjs的Dict)。但是我无法从项目的方法中访问该名称(在我的示例中为toString
)。
我可以使用常规数组,保留name属性并实现我自己的get / set / delete方法,但我宁愿使用可靠的数据结构,但我找不到它。
提前致谢:]
答案 0 :(得分:0)
Javascript对象可行。
var players = [];
players[0] = {"name":"Bob", "age":1};
players[1] = {"name":"John", "age":4};
for (var i in players) {
if (players[i].name == "Bob") {
alert("Bob is " + players[i].age);
}
}
编辑:
var players = [];
players[0] = {"name":"Bob", "age":1};
players[1] = {"name":"John", "age":4};
players.forEach(function(player){
if (player.name == "Bob") {
alert("Bob is " + player.age);
}
});
答案 1 :(得分:0)
var Players = function(){
this.players = [];
this.add = function(player){
this.players.push(player);
}
this.delete = function(name){
for(var i=0;i<this.players.length;i++)
if(this.players[i].name==name)
{
var f = this.players.slice(i+1,this.players.length+1);
this.players = this.players.slice(0,i).concat(f);
return;
}
}
this.set = function(name,player){
for(var i=0;i<this.players.length;i++)
if(this.players[i].name==name)
{
this.players[i] = player;
return;
}
}
this.show = function(){
for(var i=0;i<this.players.length;i++)
console.log(this.players[i].toString());
}
}
var p = new Players();
p.add(new Player('Lorem'));
p.add(new Player('Ipsum'));
p.show();
p.delete('Ipsum');
p.show();
答案 2 :(得分:0)
阵列的不可靠性是什么?使用内置方法IMO。一个简单的例子:
var players = [];
var Player = function(name) {
this.name = name;
this.x = 0;
this.y = 0;
this.toString = function() {
return 'player : ' + this.name + ' at ' + this.x + ', ' + this.y;
};
}
function getPlayerByName(name){
return players.filter(function(p){
return p.name.toLowerCase() === name.toLowerCase();
})[0];
}
// etc...
players.push(new Player('foo'));
var fetched = getPlayerByName('foo');
console.log(fetched);