Reputation: 2652
this is what I am trying to solve out
var name;
var totalScore;
var gamesPlayed;
var player;
var score;
//First, the object creator
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
o = {
'name' : name,
'totalScore' : totalScore,
'gamesPlayed' : gamesPlayed
};
return o;
}
//Now the object modifier
function addGameToPlayer(player,score) {
//should increment gamesPlayed by one
//and add score to totalScore
//of the gamePlayer object passed in as player
if(player == name) {
gamesPlayed += 1;
totalScore += score;
}
}
but the 2nd function where I have used if now should be something else... how can I compare this 2? ( its from an exercise to learn JS )
Upvotes: 0
Views: 186
Reputation: 506
I have attached a jsFiddle example of how this probably should work based on your sample.
//First, the object creator
function makeGamePlayer(name, totalScore, gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
o = {
'name' : name,
'totalScore' : totalScore,
'gamesPlayed' : gamesPlayed
};
return o;
}
//Now the object modifier
function addGameToPlayer(player,score) {
//should increment gamesPlayed by one
//and add score to totalScore
//of the gamePlayer object passed in as player
player.gamesPlayed += 1;
player.totalScore += score;
}
var player = makeGamePlayer("Player 1", 0, 0);
addGameToPlayer(player, 10);
alert(player.name + " Played " + player.gamesPlayed + " Total Score Of: " + player.totalScore)
I also think you have some out of scope variables (var name; var totalScore; var gamesPlayed; var score;) Keep in mind that you are wanting to manipulate the variables on the object in this case, not a set of global variables. The variables indicated in parenthesis will make maintaining your scope difficult as they are all named the same as the variables on your object and in your method calls.
Upvotes: 2
Reputation: 2625
reference properties of an object with a dot:
function addGameToPlayer(player,score) {
// this will compare player's name to global var name
if(player.name === name) {
player.gamesPlayed += 1;
player.totalScore += score;
}
}
Upvotes: 2