TypeError:记录未定义

时间:2016-11-16 06:58:36

标签: javascript cookies typeerror

我正在制作JS游戏,我必须更新高分并使用cookie显示它们。以下函数位于文件highscore.js

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(),可以处理高分等并清除游戏玩家。

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

在游戏中调用游戏时, setHighScoreTable (表)中会出现错误,错误是该记录(即table [i])未定义。需要帮助解决这个错误。

1 个答案:

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