Why does this code set the text to undefined? - javascript

Here is my JS function that sets the text to the variables. And how assign what Pokémon the player has.
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;
When I run this code it sets the text of my stats paragraphs to undefined. Even though the variables are set depending on what Pokémon they were given.
I've tried changing my code around but nothing worked.

Your code is setting the stat variables from within the setStats() function, and you are trying to access them from startGame(). Javascript is a lexical scoped language. Since you are setting the variables from withink the function, only that function can access the variables. You can fix this by moving the variables into the global scope.
(Also, you are never calling the function setStats()

Related

Javascript script does not log to browser console

I have a script but I can't figure out why it won't execute correctly.
I've declared all my variable and up to the prompts it works fine, but I can't see why it won't log the results of my functions.
var leasePriceString = prompt("Input lease price per month");
var ecoScoreString = prompt("Input eco score");
var catalogValueString = prompt("Input catalog value");
var c02String = prompt("Input C02");
var leasePrice = parseInt(leasePriceString);
var ecoScore = parseInt(ecoScoreString);
var catalogValue = parseInt(catalogValueString);
var c02 = parseInt(c02String);
var brutoMonth = true;
var VAA = true;
function calculator(){
function brutoMonthCalc(){
if (ecoScore >= 74){
brutoMonth = ((leasePrice*12)/13.92)-75;
console.log(brutoMonth);
} else {
brutoMonth = ((leasePrice*12)/13.92)-150;
console.log(brutoMonth);
}
}
function VAACalc(){
VAA = 6/7*catalogValue*(0.055+((c02-105)*0.001));
console.log(VAA);
}
brutoMonthCalc();
VAACalc();
console.log("price per month is =" + brutoMonth + VAA);
};
calculator();
I've modified some aspects of your code, and provided and explanation below:
var leasePriceString = prompt("Input lease price per month");
var ecoScoreString = prompt("Input eco score");
var catalogValueString = prompt("Input catalog value");
var c02String = prompt("Input C02");
var leasePrice = parseInt(leasePriceString);
var ecoScore = parseInt(ecoScoreString);
var catalogValue = parseInt(catalogValueString);
var c02 = parseInt(c02String);
// Declare global variables here
var brutoMonth;
var VAA;
function calculator(){
function brutoMonthCalc() {
if (ecoScore >= 74) {
brutoMonth = ((leasePrice * 12) / 13.92) - 75;
console.log(brutoMonth);
}else{
brutoMonth = ((leasePrice * 12) / 13.92) - 150;
console.log(brutoMonth);
}
}
function VAACalc() {
VAA = 6 / 7 * catalogValue * (0.055 + ((c02 - 105) * 0.001));
console.log(VAA);
}
// Call functions here
brutoMonthCalc();
VAACalc();
}
calculator();
console.log("price per month is =" + brutoMonth + VAA);
In the above code I mainly changed two things:-
Declaring global variables: You want to declare your variables only once, and then assign them in the functions that you intend to run to change their value.
Calling Functions: After you write a function, you need to call it later on. Only when you call it do the expressions in the function run.

How to access variable from a function in Javascript

I want to access variables ie. distance, vertex2Position, path which in two seperate function, inside main function called getResult. How can I achieve this without altering my code or altering my code in minimum way.
function getResult() {
document.getElementById("vertex1").onchange = function() {
var vertex1 = document.getElementById("vertex1").value;
var vertex1Position = graph.node.findIndex(e => e.id == vertex1) + 1;
document.getElementById("output").textContent = vertex1Position;
var distance = execute(vertex1Position); // How can I access distance in my result variable
};
var vertex2Position = 0;
console.log("whats here");
document.getElementById("vertex2").onchange = function() {
var vertex2 = document.getElementById("vertex2").value;
vertex2Position = graph.node.findIndex(e => e.name == vertex2)+ 1; // I also want to access vertex2Position in my result variable which is in outer function
document.getElementById("secondOutput").textContent = vertex2Position;
var path = getPath(vertex2Position); //How can I access path in var result
};
var result = distance.vertex2Position; // I want to store distance and vertex2Position in result variable
document.getElementById("searchResult").innerHTML = "test" + result + "" + path + "."; // I also want to access path
}
You should use something like this :
var container = (function(){
var distance;
var vertex2P;
return {
setDistance: function(distance){
this.distance = distance;
},
getDistance: function(){return this.distance;},
setVertex2P: function(vertex2P){
this.vertex2P = vertex2P;
},
getVertex2P: function(){return this.vertex2P;},
}}());
And then you can get and set the values in other functions like this
var result = function(){
container.setDistance(2);
container.setVertex2P(3);
console.log(container.getDistance() + container.getVertex2P());
}
result(); // 5
These are(maybe ) the best practices you can use in Javascript with this you avoid the global variables and added privacy to your variables, hope it helps you.
P.S you can short this with ECMASCRIPT 6
In javascript, you need understand about scopes. In your code, the
main scope is the getResult() function, so if you want to access
variables inside sub functions (functions inside the getResult()
function), you'll need declare the variables at beginning of this main
scope.
Example:
function getResult() {
var distance,
path,
vertex1,
vertex2,
vertex1Position,
vertex2Position = 0;
document.getElementById("vertex1").onchange = function() {
vertex1 = document.getElementById("vertex1").value;
vertex1Position = graph.node.findIndex(e => e.id == vertex1) + 1;
document.getElementById("output").textContent = vertex1Position;
distance = execute(vertex1Position);
}
document.getElementById("vertex2").onchange = function() {
vertex2 = document.getElementById("vertex2").value;
vertex2Position = graph.node.findIndex(e => e.name == vertex2)+ 1;
document.getElementById("secondOutput").textContent = vertex2Position;
path = getPath(vertex2Position); //How can I access path in var result
};
result = distance.vertex2Position;
document.getElementById("searchResult").innerHTML = "test" + result + "" + path + ".";
}
Note: You're using functions triggered by "onchange" event, so your variables will initiate as undefined, except for "vertex2Position"

I need to get a value from a variable and set is as a string

var number = +document.getElementById("tall1").value;
document.getElementById("knapp").onclick = doSomething;
function doSomething(){
var color = document.getElementById("graf1");
farge.style.height = number + "px";}
How do i get the value from var number and set it as height?
I think you should just re order your code.
document.getElementById("knapp").onclick = doSomething;
function doSomething(){
var number = +document.getElementById("tall1").value;
var color = document.getElementById("graf1");
farge.style.height = number + "px";
}

Adding multiple instances of an object to another object's array;

I am trying to add multiple instances of different objects to another object's array. I'm having trouble however.
*Creates the player*
function Player(){
this.name = "";
this.status = "Alive";
this.primaryClass = null;
this.secondaryClass = null;
this.strength = 0;
this.stamina = 0;
this.mystica = 0;
this.health = 0;
this.primaryWeapon = null;
this.offHand = null;
this.accuracy = 0;
this.block = 0;
this.baseDamage = 0;
this.maxDamage = 0;
this.attackSpeed = 0;
this.shield = null;
this.armor = null;
this.armorRating = 0;
this.exp = 0;
}
*Creates the sword weapon*
function LongSword(){
this.name = "";
this.attackSpeed = 1;
this.baseDamage = 10;
this.maxDamage = 15;
this.durability = 100;
this.block = 5;
this.exp = 0;
}
*Creates the Long Sword skills*
function Stab(){
this.name = "Stab";
this.status = "Unlocked";
this.damage = 0;
this.damageModifier = 0.75;
this.cooldown = 5;
this.exp = 0;
this.desc = "Stabs your opponent for an additional " +parseInt(this.damageModifier * 100) +"% of your base damage.";
}
*Equips the Player weapon(s)*
Player.prototype.equipWeapon = function equipWeapon(main, offHand){
if(this.primaryClass.dualWield){
this.primaryWeapon = main;
if(offHand){
this.offHand = offHand;
this.baseDamage += (this.strength + (main.baseDamage + (offHand.baseDamage / 2))) / 10;
this.maxDamage += (this.strength + (main.maxDamage + (offHand.maxDamage / 2))) / 5;
this.attackSpeed += main.attackSpeed + (offHand.attackSpeed / 2);
this.block += main.block + offHand.block;
}
}
else{
this.primaryWeapon = main;
this.offHand = null;
this.baseDamage += (this.strength + main.baseDamage) / 10;
this.maxDamage += (this.strength + main.maxDamage) / 5;
this.attackSpeed += main.attackSpeed;
this.block += main.block;
}
if(!this.primaryClass.dualWield && offHand){
console.log("Your class can not wield dual weapons.");
}
}
*Equips the Weapon skills*
LongSword.prototype.skills = function skills(skill){
this.skills = [];
skill.damage = parseFloat((this.baseDamage / skill.damageModifier).toFixed(1));
this.skills.push(skill);
}
These objects construct the basic elements of what I'm trying to do. So when I go to instantiate each one,
var Robert = new Player();
Robert.equipWeapon(new LongSword());
Robert.primaryWeapon.skills(new Stab());
I am getting the results I want. However, if I were to try to add another instance of Stab() so that it looks like this
var Robert = new Player();
Robert.equipWeapon(new LongSword());
Robert.primaryWeapon.skills(new Stab());
Robert.primaryWeapon.skills(new Stab());
I get the TypeError: Robert.primaryWeapon.skills is not a function. Why would it work correctly once, but not a second time. The end result of which I'm trying to achieve is that if consoled out Robert.primaryWeapon.skills, I should see two instances of the Stab object.
There are two issues in your Longsword's prototype.
First, you are replacing your function with your storing skill array, which have the same name :
LongSword.prototype.skills = function skills(skill){
this.skills = []; //Overrides your function
...
Which leads to your error, Robert.primaryWeapon.skills is not a function, cause once you call it, it is an array indeed.
To fix it, just change the name of one of the function or of the array.
Secondly, you are initializing your skills array to an empty array each time you call the function, resetting it every time. You should initialize it in Longsword's protoype.
Here's a an example with these fixes (fiddle with it if you want):
function LongSword(){
this.skills = [];
...
LongSword.prototype.addSkill = function skills(skill){
...
Then, you'll be able to add multiple skills :
var Robert = new Player();
Robert.equipWeapon(new LongSword());
Robert.primaryWeapon.addSkill(new Stab());
Robert.primaryWeapon.addSkill(new Stab());

javascript pull values from multiple functions

I'm practicing with event listeners and functions and am trying to build a very simple card game. My first 2 functions work to get values of card 1 and 2 once the respective buttons are clicked. I've built a third to combine the total, but having trouble pulling the generated values into a third function. My third function always returns zero. I get why, but haven't been able to find a solution to pull the values from the first 2 functions. Any help is appreciated, thanks.
var cardButton = document.getElementById('cardButton1');
var cardButton2 = document.getElementById('cardButton2');
var cardValue = document.getElementById('cardValue');
var cardValue2 = document.getElementById('cardValue2');
var cardTotalButton = document.getElementById('cardTotalButton');
var cardTotal = document.getElementById('displayTotal');
var card1Value = 0;
var card2Value = 0;
var totalCardsValue = 0;
var cardMin = 1;
var cardMax = 14;
function generateCard(){
var card1Value = randCard();
cardValue.innerHTML = 'card value is ' + card1Value;
return card1Value;
}
function generateCard2(){
var card2Value = randCard();
cardValue2.innerHTML = 'card value is ' + card2Value;
return card2Value;
}
function getPlayerTotal(){
var totalCardsValue = card1Value + card2Value;
//console.log(cardValue2 + 'test');
cardTotal.innerHTML = 'card total is ' + totalCardsValue;
}
cardButton.addEventListener('click',generateCard);
cardButton2.addEventListener('click',generateCard2);
cardTotalButton.addEventListener('click',getPlayerTotal);
function randCard(){
var genRandCard = Math.floor(Math.random()*cardMax)+1;
return genRandCard;
}
You are re-declaring your card1Value, card2Value, and totalCardsValue to a local scope. Remove the var in front of them. Doing it this way, you don't need to return any value from the generateCard() and generateCard() function because you're using the global variables.
function generateCard(){
card1Value = randCard(); //<-------Don't use var here
cardValue.innerHTML = 'card value is ' + card1Value;
return card1Value; //<-------This line is not really needed
}
function generateCard2(){
card2Value = randCard(); //<-------Don't use var here
cardValue2.innerHTML = 'card value is ' + card2Value;
return card2Value; //<-------This line is not really needed
}
function getPlayerTotal(){
totalCardsValue = card1Value + card2Value; //<-------Don't use var here
//console.log(cardValue2 + 'test');
cardTotal.innerHTML = 'card total is ' + totalCardsValue;
}

Categories