如何将1函数中给出的参数与Javascript中另一个函数的参数进行比较

时间:2012-10-29 20:57:32

标签: javascript

这就是我想要解决的问题

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

    }

但是我现在使用的第二个功能应该是别的...我怎么能比较这个2? (它来自练习JS的练习)

2 个答案:

答案 0 :(得分: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;    
    }
}

答案 1 :(得分:2)

我附上了一个jsFiddle示例,说明根据您的样本,这可能是如何工作的。

//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/

我还认为你有一些超出范围的变量(var name; var totalScore; var gamesPlayed; var score;)请记住,在这种情况下你想要操纵对象上的变量,而不是一组全局变量变量。括号中指示的变量将使维护范围变得困难,因为它们的名称与对象和方法调用中的变量的名称相同。