Whats wrong with my javascript Object? - javascript

I have a javascript "object." Im using the word object to make things easier. Which is here:
var character = {
name: "",
myClass: "",
health: 20,
maxHealth: 20,
};
Say i have a game, and the game has fights, and after each fight you gain a health point. which is done with:
character.maxHealth += 1;
However... When i tried to do this, i ended up getting 201 as the maxHealth or 2032 or 203232 or whatever number i wanted to add to the max health was just adding as if it was a string. through my eyes in looks like an integer to me but i must be mistaken. if anyone can give me a hand it would be really appreciated. That is an example of what i have. the actual code is:
var character = {
name: "",
myClass: "",
health: 20,
maxHealth: 20,
stamina: 10,
maxStamina: 10,
mana: 5,
maxMana: 5,
physStrength: 3,
minAttack: 0,
mentStrength: 3,
physDefense: 3,
mentDefense: 3,
exp: 0,
punch: function() {
toggleAttackButtons(0);
this.minAttack = this.physStrength/3;
var damage = Math.floor(Math.random() * this.physStrength) + this.minAttack;
addString("You punched and did " + damage + " damage.");
myEnemy.health -= damage;
updateStats();
setTimeout(function(){
myEnemy.attack();
toggleAttackButtons(1);
updateStats();
}, 1000);
},
kick: function(){
toggleAttackButtons(0);
this.minAttack = this.physStrength/3;
var damage = Math.floor(Math.random() * this.physStrength) + this.minAttack;
addString("You kicked and did " + damage + " damage.");
myEnemy.health -= damage
updateStats();
setTimeout(function(){
myEnemy.attack();
toggleAttackButtons(1);
updateStats();
}, 1000);
},
};
and this is where im incrementing the number:
var updateStats = function() {
document.getElementById("charHealth").innerHTML = "Health: " + character.health + " / " + character.maxHealth;
document.getElementById("enemHealth").innerHTML = "Health: " + myEnemy.health + " / " + myEnemy.maxHealth;
if(myEnemy.health <= 0){
myEnemy.health = 0;
character.maxHealth += 1;
removeFightScreen(1);
}
if(character.health <= 0){
removeFightScreen(2);
}
};
I understand the object is messy i plan on rewriting it in the future to be a lot more efficient. im just roughing it up right now.

I found myself the answer. Im sorry for my lack of code evidence, however it contains cookies, so when i write the cookies using the character stats like health and maxHealth, they end up being converted into strings to fit the cookie. Therefore i need to convert them back to integers. thank you guys for your help. Next time i will add in all the code i just felt that being there was several hundred lines of code i didnt want to go through it all.

Related

Extending and then Sorting Underscore js

I was trying to figure it out how can I extend and then sort the items by the created extension variable.
if(score === 'Overall Score'){
// let midtermSort = _.sortBy(overAll, 'overall_score');
_.each(students, function(elem) {
_.extend(elem, {overall_score : (elem.midterm_score + elem.final_score) / 2});
_.sortBy(elem, 'overall_score');
console.log(elem.firstname + " " + elem.overall_score);
});
}
As you can see on my code, I iterate to the students and then extend a new column w/c is overall_score. So right now I need to sort the items via overall_score.
Here's what I got:
As you can see the overall score does not SORT them properly. Anything i was doing wrong? Please help.
UPDATE Side Note:
I tried to mixed it up with each function and it works but it was a long process. Any idea how to refactor it a little bit?
if(score === 'Overall Score'){
let overAllScore = _.each(students, function(elem) {
_.extend(elem, {overall_score : (elem.midterm_score + elem.final_score) / 2});
});
let sorted = _.sortBy(overAllScore, 'overall_score');
_.each(sorted, function(elem) {
console.log(elem.firstname + " " + elem.final_score);
});
}
This will do what you want, assuming of course that you wanted them listed from lowest to highest overall score. Note that I've indented the code for readability:
var score = 'Overall Score';
var students = [
{
firstname: 'Frank',
midterm_score: 80,
final_score: 80
},
{
firstname: 'Julie',
midterm_score: 50,
final_score: 65
},
{
firstname: 'Eddie',
midterm_score: 100,
final_score: 73
},
{
firstname: 'Bill',
midterm_score: 60,
final_score: 67
}
];
if (score === 'Overall Score') {
_.each(
_.sortBy(
_.map(
students,
function(elem) {
return _.extend(elem, {overall_score : (elem.midterm_score + elem.final_score) / 2});
}
),
'overall_score'
),
function(elem) {
console.log(elem.firstname + " " + elem.overall_score);
}
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_.sortBy, according to the documentation, returns a sorted copy of the Array. This is unlike the standard Array.sort().
You need to keep this value:
elem = _.sortBy(elem, ...)
Or, if you want to keep the entire dataset, use map instead of each:
students = _.map(students, function(elem) {
...
return _.sortBy(elem, ...)
})

Price Variations

So how would one in JavaScript or with the added help of jQuery be able to get price variations. For example the first item is a set base at $450 and every item after that is a additional $150. But here is the trick the client is able to change that price so $450 is now $225 and additional is $75. I know how to do this with a bunch of if else statements but that just seems messy. Is there a better way?
Here's my code so far it only does the divided by two part but not the additions.
Edit: Further explanation of how this works
item#1 450
item#2 150
item#3 150
full[x] half[ ]
item#1 225
item#2 75
item#3 75
full[ ] half[x]
each additional is actually the base divided by 3 so 450 = 150 and 225 = 75 and the half is the original base 450 / 2 = 225
var dropResult;
$(function (){
$(".t").click(function(){
dropResult = $("input[name=drop]:checked").val();
dropCalculate();
});
});
function dropCalculate() {
var dropPrice = 450;
var dropAmount = $(".itemadd", "#items").length;
$("#dropAmount").html("Total: " + dropAmount);
if (dropResult == 1) {
dropTotal = dropAmount * dropPrice;
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}else {
dropTotal = dropAmount * dropPrice / 2;
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}
}
Okay, so if I understand you correctly, you want to apply a discount to the given price in a clean manner, depending on the number of items. I'd first start by applying the DRY (Don't Repeat Yourself) principle to your code, and putting variables in local scope:
//var dropResult = $("input[name=drop]:checked").val();
//this line doesn't actually do anything, so I removed it. It will always return true, as you're using the :checked pseudo-selector to only select checked checkboxes.
$(function (){
$(".t").click(function(){
dropCalculate(450);
});
});
function dropCalculate(dropPrice) {
var dropAmount = $(".itemadd", "#items").length,
dropTotal = dropAmount * dropPrice;
if (dropResult != 1) {
dropTotal = dropTotal / 2;
}
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}
Which is a lot cleaner. Then, if you have more complex discount rules, or multiple rules for multiple products, you can use an object for that. Here is a simple example of that:
$(function (){
$(".t").click(function(){
var pricesObj = {
'default': 75,
'1':450,
'2':225
};
dropCalculate(pricesObj);
});
});
function dropCalculate(priceObj) {
var dropAmount = $(".itemadd", "#items").length;
if (priceObj[dropAmount]) {
dropTotal = priceObj[dropAmount] * dropAmount;
}
else{
dropTotal = priceObj['default'] * dropAmount;
}
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}
If you need any help understanding that, just ask!
Update: I misunderstood your use case, but this should still point you in the right direction. In my code, if there is 1 product, the price is 450, 2 is 225, and more is 75 each.
a quick change you could make, it's something like that:
dropTotal = dropAmount * dropPrice;
$("#dropPrice").html("Price Total: $" + dropResult == 1 ? dropTotal.toFixed(2)) : (dropTotal / 2).toFixed(2));
check this fiddle
$('#dropPrice').text( '$' + (450 + ((450 * ($('#items .itemadd').length - 1)) / 3)) / (Number($("input[name=drop]").is(':checked')) + 1));

How to calculate interest javascript

I'm trying to create a function that returns the money I have after x years of interest.
var calculateInterest = function(total, year, rate) {
(var interest = rate / 100 + 1;
return parseFloat((total * Math.pow(interest, year)).toFixed(4))
}
console.log(calculateInterest(915, 13, 2));
I'm not getting it to work and I'm stuck!
Any advice?
You were close. You don't need parentheses around var interest:
var calculateInterest = function(total, year, rate) {
var interest = rate / 100 + 1;
return parseFloat((total * Math.pow(interest, year)).toFixed(4));
}
var answer = calculateInterest(915, 13, 2);
console.log(answer);
I'd recommend cleaning it up a little to:
var calculateInterest = function(total, years, ratePercent, roundToPlaces) {
var interestRate = ((ratePercent / 100) + 1);
return (total * Math.pow(interestRate, years)).toFixed(roundToPlaces);
}
var answer = calculateInterest(915, 13, 2, 2);
console.log(answer);
You don't need parseFloat() if the variable is already a number (it's needed when you're parsing from a string, which is not the case here). I am adding a parameter to specify how many decimal places to round to is useful so you can control the output of the function.
Updated fiddle

Javascript issues?

So here is what I have so far. I am trying to create a button that calculates percentages of test scores then displays onto the page when you press a button. Bear in mind i'm a VERY new programmer with less than 3 weeks experience and I could really use the help.
var sam = 9;
var sally = 8;
var donald = 4;
function go(){
function percentage();
alert("Sam's score on the test is " + samp + "%\nSally's score on the test is "
+ sallyp + "%\nDonald's score on the test is " + donaldp + "%")
}
function percentage(){
var samp = sam / 10 * 100;
var sallyp = sally / 10 * 100;
var donaldp = donald / 10 * 100;
}
To invoke the percentage function, remove the function keyword. The next issue is that samp, sallyp, and donaldp are scoped to the function percentage, so they're not accessible in the go function. You should make percentage take an argument
function percentage (score) {
return score / 10 * 100;
};
Then, in go:
function go () {
console.log("Sam: " + percentage(sam) + ", Sally: " + percentage(sally) +
", Donald: " + percentage(donald));
};
You can write your script as:
<script> /*writing <script type="text/javascript"> is not mandatory
as by default it will take javascript as type
Semicolon is not mandatory in JS, but it's good practice to use it
*/
var sam = 9;
var sally = 8;
var donald = 4;
function go(){
//there are different ways to print on page (alert, document.write, etc...)
alert("Sam's score: " + percentage(samp) + "Sally's score: "
+ percentage(sally) + "Donald's score: " + percentage(donald));
}
function percentage(calc){
return score / 10 * 100;
}
</script>
Other ways to print may include:
--By getting element ID:
Suppose you have a HTML element as
or
in your script, you can use:
var el_info = document.getElementById("abc"); // to get the element information
Then, you can use:
el_info.innerHTML = "Sam's score: " + percentage(samp) + "Sally's score: "
+ percentage(sally) + "Donald's score: " + percentage(donald);
or, you can directly use:
document.getElementById("abc").innerHTML = "Sam's score: " +percentage(samp)+
"Sally's score: "+ percentage(sally) + "Donald's score: " + percentage(donald));
Your variables scope is not proper.....
You have two ways to declare them. First make them global so you can access them in both functions.
Another way is to declare them inside the Go function.
According to me you should declare them into GO function.
Note : as you are working on javasceipt .you can debug your code from Console in browser when you inspect element.

Dynamically-changing variables random intergers

The numbers themselves aren't relevant. I have a list of variables that are used to track a moving vehicle.
UTC Time:, Latitude:, Longitude:, Speed:, Heading:, Steering:, Odometer:(PPM), GPS Status:, STWS Status:
Like i said the numbers aren't relevant, and neither is the math. I just need to simulate dynamically changing integers for each variable. For instance, Speed:25. then the 25 become a 26, then a 28, then a 15 and so on. I will implement this code, and then set the min and max for each variable.
I just need to show customers that the vehicle tracking system monitor can display changing values for each variable.
Thank you.
$("#the_span_id").text(n); and hook it up to a JavaScript timer event.
It sounds like what you need is a jQuery countdown. Take a look at this link:
http://www.tripwiremagazine.com/2011/04/9-cool-jquery-countdown-scripts.html
You could do something along the following lines:
var DynVar = {
variables: [],
timer: 0,
numIntervals: 0,
counter: 0,
updateVar: function(v) {
v.value = Math.random() * (v.max - v.min) + v.min;
},
createVar: function(name, min, max) {
var v = {"name": name, "min": min, "max": max};
DynVar.updateVar(v);
DynVar.variables.push(v);
return v;
},
update: function() {
for (i = 0; i < DynVar.variables.length; ++i) {
var v = DynVar.variables[i];
DynVar.updateVar(v);
console.log(DynVar.counter + ": " + v.name + ": " + v.value);
}
if (DynVar.counter++ >= DynVar.numIntervals) {
clearInterval(DynVar.timer);
}
},
start: function(interval, numIntervals) {
DynVar.counter = 0;
DynVar.numIntervals = numIntervals;
DynVar.timer = setInterval(DynVar.update, interval);
}
};
DynVar.createVar("speed", 10, 30);
DynVar.createVar("latitude", 20, 22);
DynVar.start(1000, 3);

Categories