I've got a homework assignment to correct some Javascript code that is preventing functions from being executed. I've corrected everything I can find, even used JSFiddle and JSHint to make sure. So there's no syntax errors left, but there must be a logic error because nothing is working. I'd appreciate a quick look at my code, I'm sure it's a minor issue that I'm just overlooking. Thanks!
(There's bound to be some messy code here with how many things I've tried to change around, apologies for that).
First the very basic HTML:
<body>
<p id="message"></p>
<p id="movies"></p>
<p id="object"></p>
</body>
Then the JS:
// Define variables
var output = document.getElementById("message");
var BR = "<br>";
var makeBreakfast;
var mood;
var energyLevel;
var doWork;
var powerOn;
var command;
var duration;
var quitWork;
// Define robot object
var robot = {
material: "titanium",
mood: "happy",
energyLevel: 100,
powerOn: false,
command: "Sweeping the floor",
duration: 10,
favoriteMovies: ["2001: A Space Odyssey", "The Terminator", "I, Robot", "WALL-E", "Short Circuit", "Forbidden Planet"]
};
makeBreakfast = function (newMood) {
mood = newMood;
if (mood === "Happy") {
output.innerHTML += "Here are your waffles and milk, master." + BR;
} else {
output.innerHTML += "Here is your burnt toast and lukewarm water, master." + BR;
energyLevel = 50;
}
};
doWork = function () {
if (!powerOn) {
powerOn = true;
output.innerHtml += "My current task is: " + command + ". Duration: " + duration + " minutes." + BR;
}
};
quitWork = function () {
if (powerOn) {
energyLevel = 90;
powerOn = false;
command = "Taking a nap";
}
};
// Make robot do housework
doWork();
quitWork();
The full assignment is as follows:
1) Correct the code, and make doWork and quitWork execute properly.
2) Call the makeBreakfast argument and use the string "mad" as the argument.
3) Add a new method and call it to display a string (left this part out, not helpful right now)
4) List all of the robots favorite movies, each on a new line.
5) Use named indexing syntax to add a new property called language to the robot object. Initialize it with the language of your choice.
6) Using named indexing syntax, loop through the object and list each of the property and value pairs on a new line. Display the results in a new paragraph.
I really only wanted help with #1, but if seeing the full assignment helps, this is it. Thanks everyone!
Need to make it an object, and tell the poor schmuck to make you breakfast!
(Full Difference)
// Define variables
var output = document.getElementById("message");
var movies = document.getElementById("movies");
// Define variables
var output = document.getElementById("message");
var movies = document.getElementById("movies");
var object = document.getElementById("object");
var BR = "<br>";
// Define robot object
var robot = {
material: "titanium",
mood: "Happy",
energyLevel: 100,
powerOn: false,
command: "Sweeping the floor",
duration: 10,
favoriteMovies: ["2001: A Space Odyssey", "The Terminator", "I, Robot", "WALL-E", "Short Circuit", "Forbidden Planet"],
makeBreakfast: function (newMood) {
if(newMood) this.mood = newMood;
this.command = "Making breakfast";
this.doWork();
if (this.mood === "Happy") {
output.innerHTML += "Here are your waffles and milk, master." + BR;
} else {
output.innerHTML += "Here is your burnt toast and lukewarm water, master." + BR;
this.energyLevel = 50;
}
},
doWork: function () {
if(!this.powerOn) {
this.powerOn = true;
output.innerHTML += "My current task is: " + this.command + ". Duration: " + this.duration + " minutes." + BR;
}
},
quitWork: function () {
if (this.powerOn) {
this.energyLevel = 90;
this.powerOn = false;
this.command = "Taking a nap";
output.innerHTML += "My current task is: " + this.command + ". Duration: " + this.duration + " minutes." + BR;
}
}
};
// Make robot do housework
robot.doWork();
robot.quitWork();
robot.makeBreakfast();
robot.quitWork();
robot.makeBreakfast("Mad");
robot.quitWork();
<body>
<p id="message"></p>
<p id="movies"></p>
<p id="object"></p>
</body>
Related
I am trying to solve the below Javascript kata on Codewars but getting "undefined". Can please someone show me the light on what exactly is "undefined". I am struggling to understand what is missing form my code below. Cheers.
Link to challange: https://www.codewars.com/kata/training-js-number-5-basic-data-types-object
I've searched through FreeCodeCamp JS OOP and Basic tutorials / lessons to find similar problems. Searched through StackOverflow, Reddit, and Googled many websites for similar challanges.
Code below:
function animal(name, legs, color) {
this.name = name;
this.legs = legs;
this.color = color;
}
var dog = new animal("dog", 4, "white");
// similar variables set such for other animal objects.
animal.prototype.toString = function animalToString() {
var sent = "This " + this.color + " " + this.name + " has " + this.legs + " legs.";
return sent;
}
return animal.prototype.toString.call();
Expected: This white dog has 4 legs., instead got: undefined
Try this:
function animal(obj){
var newAnimal = {
name: obj.name,
legs: obj.legs,
color: obj.color
};
return "This " + newAnimal.color + " " + newAnimal.name + " has " + newAnimal.legs + " legs.";
}
The purpose of this kata I believe is to introduce you to javascript objects. The issue is thrown when you changed the inputs of the function "animal". If you look at the sample tests in the lower right corner, the inputs being fed into the function you are trying to make should accept only one parameter which is an object with properties name, legs, and color. You changed this input into three separate parameters instead of just one.
Or you could skip the assignment altogether and just access the input directly like so:
function animal(obj){
return "This " + obj.color + " " + obj.name + " has " + obj.legs + " legs.";
}
1) Based on 'instructions'
Give you a function animal, accept 1 parameter obj like this: {name:"dog",legs:4,color:"white"} and return a string like this: "This white dog has 4 legs."
function animal({name, legs, color}) {
return `The ${color} ${name} has ${legs} legs.`;
}
2) Based on what you're supposed to learn
function animal({name, legs, color}) {
this.name = name;
this.legs = legs;
this.color = color;
}
animal.prototype.toString = function animalToString() {
return `The ${this.color} ${this.name} has ${this.legs} legs.`;
}
var dog = new animal({name:"dog", legs:4, color:"white"});
dog.toString();
function animal(obj){
return `This ${obj.color} ${obj.name} has ${obj.legs} legs.`
}
You can try this
function animal(obj){
var a={name:"dog",legs:4,color:"white"}
return "This" + " " + a.color + " " +a.name + " " + "has" + " " + a.legs + " " + "legs.";
}
I'm very new to this, and I was hoping to get some clarity in this:
Whenever I run this code (PS: boardGames, is an array in a separate doc) It seems to work, but the first answer is always "undefined". Why is that? and how can I fix it?
Thanks!
var message;
var games;
var search;
var i;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function gamestoPlay( games ) {
var topGames = '<h3> Game: ' + boardGames[i].name +'</h3>';
topGames += '<p> Minimum Players: ' + boardGames[i].idealMinPlayers + '</p>';
topGames += '<p> Maximum Players: ' + boardGames[i].idealMaxPlayers + '</p>';
return topGames
}
search = parseInt(prompt('How many people are coming?'));
for (i = 0; i < boardGames.length; i += 1) {
games = i;
if ( search >= boardGames[i].idealMinPlayers && search <= boardGames[i].idealMaxPlayers) {
message += gamestoPlay();
print(message);
}
}
Because you didn't initialize message.
When you do
message += gamesToPlay();
it first has to convert message to a string so it can concatenate to it. Since you didn't initialize message, its value is undefined, and when this is converted to a string it becomes "undefined", and then the result of gamesToPlay() is concatenated to that.
Change the initialization to:
var message = "";
I have the following Javascript in my main.js file:
//array object of API stuff
function createChartWinLoss(wins, losses) {
var pieData = [
{
value: losses,
color: "#F7464A",
highlight: "#FF5A5E",
label: "Losses"
},
{
value: wins,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Wins"
}
];
var pieOptions = {
segmentShowStroke : false,
animateScale : true
}
var winLossChart = document.getElementById('winLossChart').getContext('2d');
new Chart(winLossChart).Pie(pieData, pieOptions);
}
//creates the chart with test data
createChartWinLoss();
function summonerLookUp() {
var SUMMONER_ID = "";
var API_KEY = "keyhere";
var sumID = $("#theKey").val();
var div = document.getElementById('stuff');
var combine = "";
var array = [sumID];
var wins;
var losses;
div.innerHTML = div.innerHTML + "<br />array count: " + array.length + "<br />";
for (var i = 0; i < array.length; i++) {
combine = "";
SUMMONER_ID = array[i];
getStuff(SUMMONER_ID, combine, API_KEY, div, i);
}
}
function getStuff(SUMMONER_ID, combine, API_KEY, div, count) {
var Topuser = SUMMONER_ID;
$.ajax({
url: 'https://euw.api.pvp.net/api/lol/euw/v2.5/league/by-summoner/' + SUMMONER_ID + '/entry?api_key=' + API_KEY,
type: 'GET',
dataType: 'json',
async: false,
data: {},
success: function (json) {
var user = Topuser;
if (typeof json[user][0].queue != "undefined") {
if (json[user][0].queue == "RANKED_SOLO_5x5") {
combine = json[user][0].tier + " " + json[user][0].entries[0].division + " - " + json[user][0].entries[0].wins + " Wins " + json[user][0].entries[0].losses + " losses";
div.innerHTML = div.innerHTML + "<br />" + count + ": " + user + " " + combine;
var wins = json[user][0].entries[0].wins;
var losses = json[user][0].entries[0].losses;
//populates chart with wins losses from api
createChartWinLoss(wins,losses);
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var user = Topuser;
console.log(errorThrown);
if (errorThrown === "Not Found") {
div.innerHTML = div.innerHTML + "<br />" + count + ": " + user + " " + "UNRANKED";
}
}
});
}
And the HTML is as follows:
<div class="container">
<h2>Wins/Losses</h2>
<canvas id="winLossChart" width="400" height="200"></canvas>
</div>
As the title suggests, I am getting Uncaught TypeError: Cannot read property 'getContext' of null and I'm not entirely sure what the issue is. If I had to guess I'd say it was trying to reference something that wasn't there but I'm not 100% sure on if I am correct and how to fix it. Any advice would be great.
The line that is throwing the error is
var winLossChart = document.getElementById('winLossChart').getContext('2d');
It is saying that document.getElementById('winLossChart') does not exist.
This would be because your script is being interpreted before the elements have finished being created in the DOM.
You could either kick off the script in a window.onload function:
window.onload = function() {
createChartWinLoss();
}
Or you could put the script tag itself as the last element in the body element of your html file.
<body>
<div class="container">
<h2>Wins/Losses</h2>
<canvas id="winLossChart" width="400" height="200"></canvas>
</div>
<script src="myscript.js"></script>
</body>
Either solution would mean that the main entry point of your code (createChartWinLoss) would only happen after the other elements on the page, including the canvas, were created.
As a general process towards solving these kinds of problems, when you saw the exception in your Javascript console, you should have been able to open the stack trace, which would have led you to the fact that the error originated on the line var winLossChart = ..., which would have made you more likely to have been able to discover the source of the problem.
I was having this same problem. The element was being returned as dispHTMLUnkownElement.
The solution was to add <!DOCTYPE html>to the top of my response and then IE picked up the element type properly.
Perhaps this can help someone else...
You have to use destroy() method.
To made that you have to change a few things in your code:
var winLossChart = "";// Here you make your chart var global
function createChartWinLoss(wins, losses) {
var pieData = [{
value: losses,
color: "#F7464A",
highlight: "#FF5A5E",
label: "Losses"
}, {
value: wins,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Wins"
}];
var pieOptions = {
segmentShowStroke: false,
animateScale: true
}
//HereĀ“s the change inside the function where you run destroy().
if(typeof winLossChart.destroy != "undefined") winLossChart.destroy();
winLossChart = document.getElementById('winLossChart').getContext('2d');
new Chart(winLossChart).Pie(pieData, pieOptions);
}
//creates the chart with test data...
https://github.com/chartjs/Chart.js/issues/3231
I'm attempting to create a Choose Your Own Adventure type of game, and I'm currently trying to write a 'battle' script. What I've got so far is:
var name = "Anon";
var health = 100;
var youAttack = [name + " hits the " + opp + " with his sword", name + " uses magic!", name + " is too scared to fight!"];
var youBattle = function() {
var youBattle = youAttack[Math.floor(Math.random() * 3)];
return youBattle;
};
var opp = "Orc";
var oppHealth = 100;
var oppAttack = ["The " + opp + " hits you with his hammer!", "The " + opp + " does nothing!", "The " + opp + " back hands you!"];
var oppBattle = function() {
var oppBattle = oppAttack[Math.floor(Math.random() * 3)];
return oppBattle;
};
oppBattle();
youBattle();
I've done it like this so the opponent and player names can easily be changed.
What I'm struggling to figure out is how I can add / remove health from both the opponent and the player depending what attack is used. Obviously no health would be removed if the opp / player does nothing.
Is there a way I can do this without a bunch of messy if / else statements?
I was hoping for something easy like name + " hits the " + opp + " with his sword" + health = health - 10; but obviously that didn't work.
Thanks in advance!
http://jsbin.com/qerud/3/edit
Hope this isn't too much code:
var Attack = function(hero,opp,damageReceived,damageGiven,message){
this.message = message;
this.damageGiven = damageGiven;
this.damageReceived = damageReceived;
this.opp = opp;
this.hero = hero;
this.attack = function(opp){
this.hero.health -= damageReceived;
this.opp.health -= damageGiven;
return this.message;
};
};
var Character = function(name,health){
this.name = name;
this.health = health;
};
hero = new Character('Anon',100);
orc = new Character('Orc',150);
attack1 = new Attack(hero,orc,5,0,"The " + orc.name + " back hands you!");
attack2 = new Attack(hero,orc,0,0,hero.name + " is too scared to fight!");
attack3 = new Attack(hero,orc,15,0,"The " + orc.name + " hits you with his hammer!");
attack4 = new Attack(hero,orc,0,25,hero.name + " uses magic!");
attacks = [attack1,attack2,attack3,attack4];
while(hero.health > 0 && orc.health > 0){
console.log(attacks[Math.floor(Math.random() * 4)].attack());
console.log('Hero Health: '+ hero.health);
console.log('Orc Health: '+ orc.health);
}
if(hero.health > 0 ){
console.log(hero.name + ' won');
} else {
console.log('The ' + orc.name + ' won');
}
I can tell you first hand that trying to write this type of code uses a lot of if/else and more statements, regardless of what language you're using. You can use an array to hold the values of your attack patterns:
var attackName = ["Punch", "Sword", "Magic"]
var attackDamage = [3, 5, 4]
function youAttack(ATK, PHit) {
if(playerHit) {
playerDamage = ATK + PHit;
oppHealth = oppHealth - playerDamage;
return oppHeath;
} else {
alert("You missed!");
}
}
But, without seeing exactly what you're doing I cannot say how you should do your attacks and damages. I can only assume. You will need a system of evaluating attacks, misses, etc. that does use IF/ELSE Statements at least somewhere.
Ok so I think the problem with my code is related to the actual html page i'm activating the code with, but i can't be sure.
what i'm trying to do is have two questions asked via an array. I want the second question to show "gerp" instead of correct and for it to notify you is you are wrong on question two if you are wrong.
this is what i use on the page to start the "riddles" :
<button onclick="myFunction()">Click Me</button>
<p id="demo"></p>
and this is the code i use in the js file that is separate to the html file (sorry if i sound silly, i'm just trying to be specific):
var i = 0;
var myArray = [{
q: "What was her favorite Color?",
a: "purple" }, {
q: "gymhoaccetpptfe",
a: "rev six nine eleven"}];
function myFunction() {
var x;
var name = prompt(myArray[i].q);
if (name == myArray[i].a) {
x = document.getElementById("demo").innerHTML + " " + "Correct!" + " " + "Listen!"
+ " " +
"http://www.npr.org/2010/02/12/123534818/carl-sagan-and-ann-druyans-ultimate-mix-tape"
;
i= i + 1 ;
document.getElementById("demo").innerHTML = x;
} else if ((name == myArray[i + 1].a)) {
x = document.getElementById("demo").innerHTML + " " + "gerp!";
document.getElementById("demo").innerHTML = x;
} else {
x = document.getElementById("demo").innerHTML + name + " " + "is" + " " + "wrong!";
document.getElementById("demo").innerHTML = x;
}
}
I just want "Gerp" to show up when the second question is answered correctly.
it's because in the first if, you do i=i+1, but in the second if, for the gerp, you're checking for i + 1, which would be 2, the third element. unless you need it to be dynamic, just use the corresponding index:
... else if(name == myArray[1].a) { ...
You should really consider fixing your formatting and cleaning up your code. It'll look much nicer and errors will be easier to spot:
var questions = [{
question: 'What was her favorite Color?',
answer: 'purple',
message: 'Correct! Listen: http://www.npr.org/2010/02/12/123534818/carl-sagan-and-ann-druyans-ultimate-mix-tape'
}, {
question: 'gymhoaccetpptfe',
answer: 'rev six nine eleven',
message: 'gerp!'
}];
function add_message(text) {
var element = document.createElement('div');
var demo = document.getElementById('demo');
element.innerHTML = text;
demo.appendChild(element);
}
function ask_questions(questions) {
for (var i = 0; i < questions.length; ) {
var question = questions[i];
var response = prompt(question.question);
if (response == question.answer) {
add_message(question.message);
i++;
} else {
add_message('"' + response + '" is wrong!');
}
}
}
function start_riddles() {
ask_questions(questions);
}