在Object Orient JS中,我正在尝试动态地将对象添加到数组中

时间:2014-02-19 15:58:12

标签: javascript arrays

以下代码适用于非常简单的游戏。我在尝试着 动态地将玩家对象添加到玩家阵列中。 基本上添加这个......     {playerName:'Ziggy',playerId:0}, 进入这...     this.Players = [];

代码相当简单且不言自明。 在玩家阵列中硬编码的玩家是 就在那里帮我解决问题。

var BobsGame = function(){
this.Players = [
   {playerName:'Ziggy', playerId:0},
   {playerName:'Mark', playerId:1}];
}

var Player = function(name, id){
    this.playerName = name;
    this.playerId = id; 
}

BobsGame.prototype.addPlayer = function(Player, id){
    this.playerName = Player;
    this.playerId = id;
    this.Players.push(this.playerName, this.playerId);
    //alert('Player ' + name + ' with an id of ' + i  + 'has been created');
}

var myGame = new BobsGame();

$('#addPlayer').click(function(){
    id = myGame.Players.length;
    name =  $('#addPlayerName').val();
    newPlayer = new Player(name, id);
    myGame.addPlayer(newPlayer, id);
    alert(JSON.stringify(myGame.Players, null, 4));
})

问题出在AddPlayer函数中,我猜?我已经尝试了几个差异变化上面的但不起作用。谢谢!

1 个答案:

答案 0 :(得分:3)

而不是myGame.addPlayer(newPlayer, id);只做myGame.addPlayer(newPlayer);

然后addPlayer函数只需要:

BobsGame.prototype.addPlayer = function(Player){
    this.Players.push(Player);
}

然后你实际上把那个对象放入数组中,你可以使用它来获取name / id。

除非出于某种原因,否则您只需要名称和ID,在这种情况下:

myGame.addPlayer(newPlayer); //No need to pass the id as well, as it's in the newPlayer object

BobsGame.prototype.addPlayer = function(Player){
    this.Players.push({name:Player.playerName,id:Player.playerId});
    // or - this.Players.push([Player.playerName,Player.playerId]);
}

为简单起见,我会将Player对象的属性更改为nameid以简化引用。这样您就可以player.name代替player.playerName