gpt4 book ai didi

javascript - 类型错误:记录未定义

转载 作者:行者123 更新时间:2023-12-03 05:39:07 25 4
gpt4 key购买 nike

我正在制作一个 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);
}

游戏中调用gameover时,setHighScoreTable(table)发生错误,错误是记录(即table[i])未定义。需要帮助解决此错误。

最佳答案

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

关于javascript - 类型错误:记录未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40625850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com