gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'Wins' of undefined?

转载 作者:行者123 更新时间:2023-12-03 02:36:01 25 4
gpt4 key购买 nike

我已经得到了这些对象,并且已经正确调用了它们,但我不断收到这些错误。有人知道为什么吗?它说来自玩家对象的“胜利”未定义,但显然是定义的。

这是我在控制台中调用 startGame(); 时显示的内容。

script.js:56 undefined has NaN left.
script.js:58 Almighty Grant has NaN left.

var playerName = prompt('Name your character');

var player = {
Name: playerName,
Health: 40,
HealsLeft: 2,
Wins: 0,
attackDamage: function(num) {
return Math.floor(Math.random() * 2) + 1;
},
healsRandom: function(num) {
return Math.floor(Math.random() * 9) + 1;
}
};

console.log(player.healsRandom());

最佳答案

添加@Jeff Matthews 的答案,即使您在创建播放器后调用了 startCombat() 。还是不行,为什么?

问题出在您的 startCombat 函数上。

function startCombat() {
while (player.Wins < 5 && player.Health > 0) {
attackOrQuit = prompt('Do you want to attack, heal or quit?');
if (attackOrQuit === "heal") {
player.Health += player.healsRandom;
this.HealsLeft--;
console.log(player.Name + " has healed and has " + player.Health + " health.")
} else if (attackOrQuit === "quit") {
break;
}

...

您正在使用 player 变量,结果发现该变量未初始化!你不相信我吗?在这里:D

startCombat 中,JavaScript 尝试查找名称 player,它在全局范围内找到该名称。是的,在这里:

var i = 0;
var playerName;
var attackOrQuit;
var player; // <-- here

但是我已经在 startGame 函数中初始化了它?!

是的,您已经做到了,但只是有一点问题。

startGame 中,您在初始化 player 方面做得很好,但只有一件事,您使用了 var,这意味着,您在 startGame 函数的范围下创建一个名为 player 的新变量

这样您创建的 player 变量就只能在 startGame 的范围内使用。

一种解决方案是省略 var

player = {
Name: playerName,
Health: 40,
HealsLeft: 2,
Wins: 0,
attackDamage: function (){
return Math.floor(Math.random() * 2) + 1;
},
healsRandom: function () {
return Math.floor(Math.random() * 9) + 1;
}
};

当你省略var时,JavaScript将查找该变量,而不是创建一个新变量,如果没有找到,它将创建一个新的全局变量范围变量,否则,它将修改它找到的变量。

您还有在另一个函数上使用的其他变量,这些变量在全局范围内不可用。与opponent 变量一样,它只是startCombat 内的局部变量。 (是的,其他函数不认识它们!)

简单解释正在发生的事情:

var i = 0;

function start() {
var i = 1; // <-- creates a new variable `i` in its own scope
startAgain();
}

function startAgain() {
console.log(i); // <-- no variable `i` found in its scope, so let's find some in the global scope.
// looks like it found one; with a value of `0`
}

start();

这将输出0

注意:我不确定我使用的术语,这只是我表达正在发生的事情的方式;任何更正都很好!

更新

未使用 var 关键字,但 JavaScript 未找到该变量示例:

function start() {
i = 1; // <-- JavaScript tries to find `i`
// <-- it founds none, well, let's make this a `global scope` variable
startAgain();
}

function startAgain() {
console.log(i);
}

这将输出1

更新

您的计算错误,您正在向 Health 添加一个 function 指针。

这里:

player.Health +=  player.healsRandom;

应该是:

player.Health +=  player.healsRandom();

player.attackDamageopponent.attackDamage执行相同的操作

关于javascript - 类型错误 : Cannot read property 'Wins' of undefined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48532765/

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