0

这就是我要解决的问题

    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;    
        }

    }

但是如果现在我使用的第二个函数应该是别的东西......我该如何比较这两个?(它来自学习 JS 的练习)

4

2 回答 2

2

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)

http://jsfiddle.net/brBx9/

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.

于 2012-10-29T21:10:02.040 回答
2

带点的对象的引用属性:

function addGameToPlayer(player,score) {

    // this will compare player's name to global var name
    if(player.name === name) {
         player.gamesPlayed += 1;
         player.totalScore += score;    
    }
}
于 2012-10-29T21:02:55.163 回答