2012-08-10 75 views
0

我一直在研究codecademy中的Javascript,並對其中一個問題有疑問。在Javascript中使用對象

問:

寫兩個功能:

one creates an object from arguments 
the other modifies that object 

我的回答:

//First, the object creator 
function makeGamePlayer(name,totalScore,gamesPlayed) { 
    //should return an object with three keys: 
    // name 
    // totalScore 
    // gamesPlayed 
    var myObject = { 
    "name": name, 
    "totalscore" : totalscore, 
    "gamesPlayed" : gamesPlayed 
    }; 
    return myObject; 
} 

//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 
    var score = player[totalscore]; 
    score =score+1; 
    player[totalscore] = score; 
} 

不知道在我的錯誤。需要改善這種解決方案..非常感謝一些指導...

在你的對象
+1

有什麼問題時?如果你不知道錯誤是什麼,我們應該猜測它? – Th0rndike 2012-08-10 15:01:54

+2

你說你必須給'player.totalscore'添加'score',但是你將'score + 1'分配給'player.totalscore'。另外,要小心括號記號,因爲它需要字符串:'player [「totalscore」]',而不是'player [totalscore]'。 – 2012-08-10 15:02:41

+2

您應該在練習時閱讀[MDN JavaScript指南](https://developer.mozilla.org/en-US/docs/JavaScri)。尤其要看[使用對象](https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects)。 – 2012-08-10 15:10:27

回答

4

你永遠不會分配比分

"totalscore" : totalscore, 

應該

"totalscore" : totalScore 

,因爲你是傳遞totalScore

3

您沒有正確訪問對象,要麼

var score = player.totalscore; 

var score = player["totalscore"]; 

它需要一個字符串,但你傳遞一個未定義的變量。

您還在函數中定義了score兩次,對內部變量使用不同的名稱。

1

參數makeGamePlayer被命名爲totalScore,但是您使用totalscoremyObject這是一個不同的名稱 - 案件事宜。

你也有一個問題,在addGameToPlayer試圖使用一個名爲totalscore變量,但未定義

0

除錯字的,你的代碼是相當愚蠢的和毫無意義的國際海事組織(對不起,但谷歌道格拉斯Crockford的JavaScript對象或東西和閱讀什麼是powerconstructor是),我收集你想檢查是否所有參數傳遞給函數。如果是這樣的:

function foo (bar, foobar) 
{ 
    if (arguments.length < 2) 
    { 
     throw new Error('foo expects 2 arguments, only '+arguments.length+' were specified'); 
    } 
    //or - default values: 
    bar = bar || 'defaultBar'; 
    //check the type? 
    if (typeof bar !== 'string' || typeof foobar !== 'number') 
    { 
     throw new Error ('types don\'t match expected types'); 
    } 
} 

等等......但是,請閱讀並更具體問一個問題