我正在製作一個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中需要幫助。
你不應該寫'的getCookie( cookie_name);'而不是'getCookie(「cookie_name」);'? – gus27
你可以做'scoreTable.push(record); scoreTable.sort((a,b)=> a.score - b.score);' – Tibrogargan
除此'getCookie(cookie_name)'之外,我在代碼中看不到任何問題。你能提供確切的錯誤信息和錯誤出現的地方嗎? – gus27