Having Trouble Understanding Javascript Methods - javascript

This is my current assignment :
Add a method that will increase the value of one of the numeric properties.
Add a method that will decrease the value of the same numeric property.
Create a for loop after creating an instance of the character. The loop will iterate 100 times.
Inside the loop call one of the methods based on a random number from zero to 3. Using a switch statement, if the value is 0 then call the method that losses; 1 don’t call anything; 2 call the method that gains.
Here is my current coding. I know I'm doing something wrong. I just can't figure out what I am doing wrong with the switch statement.
var BR = "<br />";
function person(name, sandwiches) {
this.name = name;
this.sandwiches = sandwiches;
function jump() {
var text = " leaps over an obstacle.";
return fname + text;
}
function run() {
var text = " runs as fast as they can";
return fname + text;
}
function dodge() {
var attack = math.random();
var att = math.round(attack);
var defense = math.random();
var def = math.round(defense);
if(att > def) {
return "You missed";
}
else {
return "You dodged";
}
}
function date() {
var today = new Date();
return today.toDateString();
}
function shout() {
var word = "Oh no";
return word.toUpperCase();
}
this.addSandwich = function (sandwiches) {
sandwiches = sandwiches + 1;
return sandwiches;
};
this.loseSandwich = function (sandwiches) {
sandwiches = sandwiches - 1;
return sandwiches;
};
}
var character = new person("Jerry", 1);
for(i=0; i < 100; i++) {
var random = Math.floor(Math.random() * 3);
switch(random) {
case 0:
character.loseSandwich(character.sandwiches);
console.log(sandwiches);
break;
case 1:
break;
case 2:
character.addSandwich(character.sandwiches);
break;
}
}
document.write("Name: " + character.name + BR);
document.write("Sandwiches: " + character.sandwiches + BR);

Math.floor(Math.random() * 3) is not what you want.
You want something like Math.random() % 3 to get 0, 1, or 2 every single time

Not sure if this is your problem, but it is at least one of them;
In a few places you have a lowercase math, for example:
function dodge() {
var attack = math.random();
JavaScript is case-sensitive, and it should be Math.random() not math.random()
Another issue is that these functions:
this.addSandwich = function (sandwiches) {
sandwiches = sandwiches + 1;
return sandwiches;
};
do not change the number of sandwiches. You get in a value of sandwiches, add or subtract 1, then return that changed number, but never use the returned result.
You are only changing the value of the variable that was passed in, not changing the number of sandwiches on the instance of the person.
Note that this.sandwiches (the variable on the instance of a person) is not the same variable as sandwiches (the function argument)
I dont think there is any reason to pass the number of sandwiches into those functions, and they could just do:
this.addSandwich = function () {
this.sandwiches = this.sandwiches + 1;
};
or more simply:
this.addSandwich = function () {
this.sandwiches++;
};
Another problem here:
character.loseSandwich(character.sandwiches);
console.log(sandwiches);
The console.log statement is trying to log sandwiches but that is not a variable at that point. You probably wanted console.log(character.sandwiches); However this wouldn't cause an exception, it would just always log undefined.

Related

How to get a new random number in javascript

I am very new to JavaScript and I'm sure this question has been answered quite a bit, but when I search my question I don't seem to find an answer (or one that I actually understand :D)
Currently, I'm trying to create a tool to help kids with there multiplication facts and I'm having trouble getting the program to generate new random numbers.
var r1 = Math.floor(Math.random() * 13);
var r2 = Math.floor(Math.random() * 13);
function start() {
println("Welcome to the multipilcation helper! ");
var num = readLine("Pick a number you want to practice or type 'random'!");
var ques = readLine("How many questions do you want?");
if (num == "random") {
for (var i = 0; i < ques; i++) {
var answer = r1 * r2;
println(r1 + "*" + r2);
var check = readLine("what is the answer");
if (check == answer) {
println("thats correct!");
} else {
println("thats wrong! ");
}
}
}
}
The problem is that my variables seem to pick a random number as soon as the script starts and stick with it instead of giving me a new random number.
Can anyone help me out and tell me how to get a new random number every time the variable is called?
Simply create yourself a method like the one below and use it like r() to get a new random number every call.
function r() {
return Math.floor(Math.random() * 13);
}
console.log(r());
console.log(r());
console.log(r());
In your loop you should be reassigning the random numbers so that they are reassigned every iteration of the loop. Otherwise they stay static to the value you give them at the top.
Also, you should use triple equals in Javascript when checking for equality as it is best practice.
function start() {
console.log("Welcome to the multipilcation helper! ");
var num = prompt("Pick a number you want to practice or type 'random'!");
var ques = prompt("How many questions do you want?");
if (num == "random") {
for (var i = 0; i < ques; i++) {
var r1 = Math.floor(Math.random() * 13);
var r2 = Math.floor(Math.random() * 13);
var answer = r1 * r2;
console.log(r1 + "*" + r2);
var check = prompt("what is the answer");
if (check == answer) {
console.log("thats correct!");
} else {
console.log("thats wrong! ");
}
}
}
}
start()
You random numbers are being static at the moment. They need to be called again. Move your r1 and r2 assignments inside the for.
I don't have enough reputation to comment, but will update the answer
if you explain it with more details.
You need to put the random call in a function in order for it to create a new number each time. When you assign it directly to a variable as you have, it only runs once and stores that value in the variable.
// pick a number between 0 and 13
var random = function() {
return Math.floor(Math.random() * 13);
}
function start(){
for(var i = 0; i < 15; i++){
// call random function for each number and store in a var
var number1 = random();
var number2 = random();
var answer = number1 * number2;
console.log('equation:', number1 + '*' + number2);
console.log('answer:', answer);
}
}
// call the start function
start()

Javascript: How to get the value of a function?

I am making a quick game where a player damages a enemy npc. I have a function below that does the calculation for the damage, but I can't get the console log to say i'm doing "X" amount of damage. What am I doing wrong? Instead, it just pulls up the function statement, but I want it to give me the functions value!
var damage = function() {
return Math.floor(Math.random() * 5 + 1);
};
I'm calling my function in another code properly, but when I try to console log the damage in that other code, I get a error.
function attackButton() {
darkwarrior.hp = darkwarrior.hp - damage();
console.log(darkwarrior.hp);
console.log(damage);
If you run console.log(damage()); you will get the "X" amount of damage instead of the function statement. So you could change attackButton() function to be:
function attackButton() {
var damageDealt = damage();
darkwarrior.hp = darkwarrior.hp - damageDealt;
console.log(darkwarrior.hp);
console.log(damageDealt);
I'm not sure to understand, you want to log the result? If so, you can do that:
var damage = function() {
return Math.floor(Math.random() * 5 + 1);
};
console.log(damage());
EDIT:
you forgot the (). + the value will not be the same if you don't put it in a variable:
function attackButton() {
var amount = damage()
darkwarrior.hp = darkwarrior.hp - amount;
console.log(darkwarrior.hp);
console.log(amount);
}
you just have to use an expression to assign the value to a variable. Then log it. Then return it.
var damage = function() {
var num = Math.floor(Math.random() * 5 + 1);
console.log(num);
return num;
};
damage();
Something like this should work for you.
function NPC(startingLife, name) {
this.hp = startingLife;
this.name = name
}
NPC.prototype.takeDamage = function(amount) {
this.hp = Math.max(this.hp - amount, 0);
if (this.hp == 0) {
console.log(this.name + " Dies");
}
return this.hp;
};
function damage() {
return Math.floor(Math.random() * 5 + 1);
}
var darkwarrior = new NPC(4, 'Dark Warrior');
function attackButton() {
var amount = damage();
darkwarrior.takeDamage(amount);
console.log("Dark Warrior took " + amount + " points of damage");
}
document.querySelector('#attack-button').addEventListener("click", attackButton);
<button id="attack-button">ATTACK!</button>
You are just returning the value instead of printing it. You should instead replace return with console.log(

Reverse order of an array and return the size of it javascript

I have a strange problem. I have to implement a function count(s) which inverts the getNumberSequence function that I have already create. (i.e: count(getNumberSequence(x)) == x, for all integers x > 0). I have my function and I have also the logic to resolve the problem but I don't know how to do it. In my case I want to call the previous string of ordered numbers, split them and call the last number. The problem is, how can I call the return of another method? Here are my codes:
function getNumberSequence(number) {
var result = "";
if (number <= 0) {
return result;
} else {
var first = true;
for (i = 1; i <= number; i++) {
if (first) {
first = false;
} else {
result += ", ";
}
result += i;
}
}
return result
}
Basically I need the variable result in this case to call it in the other function.
function count(s) {
var d = s. split(', ');
return d[-1];
}
I know that the second code is wrong but I don't know how to fix it. I have implemented a test that is:
test( "Count", function() {
for (i = 1; i<10000; i = i + 10) {
equal(count(getNumberSequence(i)) , i, "count(getNumberSequence(" +i + ")) should return " + i);
}
I know that the answer could be stupid but I started javascript yesterday for the first time. Hope you can help me. Thanks to everyone
If I understand you correctly you want to pass a number, say 10, into the first function and have that return a string of numbers up to 10 and then for count to read that string and return 10 (as an integer) again? This will do the trick. It takes the string, splits it, and pops out the last number converting it to an integer before it returns it.
function count(seq) {
return parseInt(seq.split(', ').pop(), 10);
}
I could rewrite it like this:
function count(seq) {
// create an array
var arr = seq.split(', ');
// grab the last element (a string)
var lastElement = arr.pop();
// convert the string to an integer
var convertedInteger = parseInt(lastElement, 10);
// return the integer
return convertedInteger;
}
If you wanted to use reverse and grab the first element, do this:
function count(seq) {
return parseInt(seq.split(', ').reverse()[0], 10);
}
Or use shift which does the same thing:
function count(seq) {
return parseInt(seq.split(', ').reverse().shift(), 10);
}
DEMO

Javascript error with returns and multiple the return

And I am sorry to bother with this noob-stuff, but currently new to all this. But learning slowly.
In the first lines of code im getting a return (in this code i get 20*2=40. in the next phase I want to multiplie the return (40) with 20. = 800. so in the outcome it will show 40 And 800. But i only get it to be in the outbox [function], it says. and a msg; "it looks like you didnt print out a value for newNumber".
What do I do wrong? Thanks for all help!
var timesTwo = function (number) {
return number * 2;
};
timesTwo(20);
var newNumber = function (tal) {
(timesTwo * tal);
console.log(newNumber);
};
newNumber(20);
What you need to do is assign the result to a variable, and in the second function return the result:
var timesTwo = function(number) {
return number * 2;
};
var twoTimesResult = timesTwo(20);
var newNumber = function (tal) {
return twoTimesResult * tal;
};
var result2 = newNumber(20);
console.log(result2);
If you wanted to be fancy you could also do the following:
function multiplier(num, multiplier) {
var by = num * multiplier;
return function (number) {
return number * by;
};
}
var multiplyResult = multiplier(20, 2);
console.log(multiplyResult(20));
I'm answering this question too because I think these types of things are fun.
Another approach you could take is the OOP approach.
From your example you have a common multiplier of 20 and a beginning constant of 2.
I would personally attack this problem like so to avoid multiple variables:
// Create a calc object
var Calc = (function () {
// Constructor
Calc = function () {
// Initial constant
this.current_val = 2;
}
// Prototype methods
Calc.prototype = {
// inc() method
inc: function () {
return this.current_val * 20;
}
}
// Return object
return Calc;
})();
// Object Instance
var obj = new Calc();
// Initial call to inc() -> 40
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
// Second call to inc() -> 800
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
// Third call to inc() -> 16000
obj.current_val = obj.inc();
// Log
console.log(obj.current_val);
I made a jsfiddle so you can see the output.

JavaScript: returning NaN (Part 2)

(note this is similar to but not the same as the question I asked moments ago - the solution to that question was to add the brackets when calling Math.Random)
At the bottom of the code below, I'm dealing out two hands of blackjack myhand and yourhand and then logging the hands to the console
"I scored a "+myHand.score()+" and you scored a "+ yourHand.score());
However, the result I'm getting is
I scored NaN and you scored a NaN
Originally, the getValue method in the Card constructor was passed a parameter called card but the instructions for building the Hand constructor said to call getValue without passing a parameter
this.card1.getValue();
so I changed the getValue method to take the var number (which is in the Card constructor)
anyways, to make a long story short, whatever i do, it's printing out
I scored NaN and you scored a NaN
and I'm not sure exactly where I'm going wrong.
// Make your card constructor again here, but make sure to use private
// variables!
function Card(num, suit){
var number = num;
var suits = suit;
this.getSuit = function(){
return suits;
};
this.getNumber = function(){
return number;
};
this.getValue = function(number){
if (number > 10){
return 10;
}else if (number === 1){
return 11;
}else{
return number;
}
};
}
function Hand(){
this.card1 = deal();
this.card2 = deal();
this.score = function(){
var score1 = this.card1.getValue();
var score2 = this.card2.getValue();
return score1 + score2;
};
}
// Make a deal function here. It should return a new card with a suit
// that is a random number from 1 to 4, and a number that is a random
// number between 1 and 13
var deal = function(){
var suit = Math.floor(Math.random() * 4 + 1);
var number = Math.floor(Math.random() * 13 + 1);
return new Card(number, suit);
};
// examples of the deal function in action
var myHand = new Hand();
var yourHand = new Hand();
console.log("I scored a "+myHand.score()+" and you scored a "+ yourHand.score());
Your getValue function is wrong. It should be:
this.getValue = function() {
if( this.number>10) return 10;
if( this.number==1) return 11;
return this.number;
}
A hint that something was wrong is that you are calling this.card1.getValue() with no arguments, whereas you defined this.getValue(number) with an argument.
When you address card.getValue() it requires some input
this.getValue = function(number){
if (number > 10){
return 10;
}else if (number === 1){
return 11;
}else{
return number;
}
};
The function doest not return anything, resulting in a NaN.
To solve this, use this.number instead
Your get value function accepts a number argument
this.getValue = function(number)
But you aren't passing in the value here:
var score1 = this.card1.getValue();
var score2 = this.card2.getValue();

Categories