2016-11-16 71 views
0

我正在制作一个JS游戏,我必须更新高分并使用cookie显示它们。下面的功能是在一个文件highscore.jsTypeError:记录未定义

function getHighScoreTable() { 
    var table = new Array(); 
    for (var i = 0; i < 10; i++) { 
     // Contruct the cookie name 
     var cookie_name = "player" + i; 
     // Get the cookie value using the cookie name 
     var cookie_value = getCookie(cookie_name); 
     // If the cookie does not exist exit from the for loop 
     if (!cookie_value) { 
      break; 
     } 
     // Extract the name and score of the player from the cookie value 
     var value_array = cookie_value.split("~"); 
     var pname = value_array[0]; 
     var pscore = value_array[1]; 
     // Add a new score record at the end of the array 
     table.push(new ScoreRecord(pname, pscore)); 
    } 
    return table; 
} 
// 
// This function stores the high score table to the cookies 
// 
function setHighScoreTable(table) { 
    for (var i = 0; i < 10; i++) { 
     // If i is more than the length of the high score table exit 
     // from the for loop 
     if (i >= table.length) break; 
     // Contruct the cookie name 
     var cookie_name = "player" + i; 
     var record = table[i]; 
     var cookie_value = record.name + "~" + record.score; // **error here = TypeError: record is undefined** 
     // Store the ith record as a cookie using the cookie name 
     setCookie(cookie_name, cookie_value); 
    } 
} 
在我game.js

,我有一个函数GAMEOVER(),它处理的高分等,并清除gametimers。

function gameOver() { 
    clearInterval(gameInterval); 
    clearInterval(timeInterval); 
    alert("game over!"); 
    var scoreTable = getHighScoreTable(); 
    var record = ScoreRecord(playerName, score); 
    var insertIndex = 0; 
    for (var i = 0; i < scoreTable.length; i++) { 
     if (score >= scoreTable[i].score) { 
      insertIndex = i; 
      break; 
     } 
    } 
    if (scoreTable.length == 0) { 
     scoreTable.push(record); 
    } else { 
     scoreTable.splice(insertIndex, 0, record); 
    } 
    setHighScoreTable(scoreTable); 
    showHighScoreTable(scoreTable); 
} 

当GAMEOVER被称为在游戏中,在setHighScoreTable(表)发生错误,并且错误是记录(即表[1])是未定义的。在这个bug中需要帮助。

+1

你不应该写'的getCookie( cookie_name);'而不是'getCookie(“cookie_name”);'? – gus27

+0

你可以做'scoreTable.push(record); scoreTable.sort((a,b)=> a.score - b.score);' – Tibrogargan

+0

除此'getCookie(cookie_name)'之外,我在代码中看不到任何问题。你能提供确切的错误信息和错误出现的地方吗? – gus27

回答

1

假设ScoreRecord的定义是这样的:

function ScoreRecord(name, score) { 
    this.name = name; 
    this.score = score; 
} 

问题是你正在做的:

record = ScoreRecord(playerName, score); 

这将只是调用构造函数,就好像它是一个功能 - 但它没有返回值。只需添加new关键字来创建,而不是

record = new ScoreRecord(playerName, score); 

你也可以做这样的事情,以防止构造函数被调用的正常功能新的对象:

function ScoreRecord(name, score) { 
    "use strict" 

    if (!(this instanceof ScoreRecord)) { 
     throw new Error("ScoreRecord must be called with the new keyword"); 
    } 
    this.name = name; 
    this.score = score; 
} 
+0

是的,如果它超出table.length,我有中断代码 –

相关问题