这是我的JS函数,它将文本设置为变量。如何分配玩家拥有的神奇宝贝。
function setStats() {
// Sets up stats based on Pokemon
if (computerPokemon === 'Pikachu') {
var computerAttack = 30;
var computerUlt = 60; // Does damage
var computerHealth = 50;
var computerSpeed = 20;
var computerAgility = 10;
}
if (playerPokemon === 'Ho-Oh') {
var playerAttack = 70;
var playerUlt = 10; // Buffs HP
var playerHealth = 80;
var playerSpeed = 35;
var playerAgility = 12;
}
document.getElementById("pHP").innerHTML = 'Health: ' + playerHealth;
document.getElementById("pSpeed").innerHTML = 'Speed: ' + playerSpeed;
document.getElementById("pAgility").innerHTML = 'Agility: ' + playerAgility;
}
function startGame() {
// Player Pokemon Selector
var playerPokemonArray = ["Ho-Oh","Venusaur","Weedle"];
var playerPokemonArrayRandom = Math.floor((Math.random() * playerPokemonArray.length));
var playerPokemon = playerPokemonArray[playerPokemonArrayRandom];
document.getElementById("playerPokemon").innerHTML = 'Your Pokemon is: ' + playerPokemon;
// Computer Pokemon Selector
var computerPokemonArray = ["Pikachu","Charmander","Diglett"];
var computerPokemonArrayRandom = Math.floor((Math.random() * computerPokemonArray.length));
var computerPokemon = computerPokemonArray[computerPokemonArrayRandom];
document.getElementById("computerPokemon").innerHTML = 'The Computer\'s Pokemon is: ' + computerPokemon;
当我运行此代码时,它会将我的统计信息段落的文本设置为undefined。即使变量的设置取决于他们给出的神奇宝贝。
我尝试过改变我的代码,但没有任何效果。
答案 0 :(得分:0)
您的代码正在startGame()
函数中设置统计变量,并且您正尝试从setStats()
访问它们。 Javascript是一种词法范围的语言。由于您正在使用函数设置变量,因此只有该函数才能访问变量。您可以通过将变量移动到全局范围来解决此问题。
(另外,你永远不会调用函数{{1}}