Javascript issues? - javascript

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.

Related

adding and subtracting to the array range

Hey I have a question about this piece of code that I have:
var levelsRange = arrayeventslevel[0] + " through " + arrayeventslevel[arrayeventslevel.length-1]; ;
$("#existorders").html(
"There are currently: " + arrayeventslength.length +
" events on " + dayoftheweek +
"<br/>" + " with order levels: " + levelsRange +
"<br />" + "You can move new event to levels ranging between: " + newLevelsRange
);
currently levelsRange outputs for example 1 through 6 range. If that is the case,
I need another variable newLevelsRange that should say 0 through 7 based on initial variable range.
However, if levelsRangesays 0 through 6, new variable should say 0 through 7 NOT -1 through 7
I am having trouble adding subtracting properly from initial variable information. Can someone please assist.
var newLevelsRange=(arrayeventslevel[0]||1)-1 + " through " + (arrayeventslevel[arrayeventslevel.length-1]-1);
Simply check if the first element is zero, if so, take 1...
I just did this
if(arrayeventslevel[0] != 0){
arrayeventslevel[0] = arrayeventslevel[0] - 1;
arrayeventslevel.length =arrayeventslevel.length + 1;
}
var newLevelRange = arrayeventslevel[0] + " through " + arrayeventslevel.length;
not sure how to use Math.max

why is this while loop causing an infinite loop?

For some reason I'm having difficulty getting this while loop to work. It keeps crashing my browser whenever I try to test it out, and in the one case that I was able to see the results of the loop in the console, all I saw was NaN printed several times. Is there something I've forgotten in my code?
<div id="output"></div>
<script>
var starting = prompt("What is your starting balance?");
var target = prompt("What is your target balance?");
var interest = prompt("What is your interest rate?");
var periods = 0;
var current = starting;
var greaterThan = false;
while (greaterThan === false) {
if (current < target) {
current = current + (current * interest);
periods++;
} else {
greaterThan = true;
alert("it took " + periods + " periods to make your starting balance greater than your target balance.");
document.querySelector('#output').textContent = "to grow an initial investment of " + starting + " to " + target + " at a " + interest + " interest rate will require " + periods + " investment periods.";
}
}
</script>
The one problem I could see is, all your input values are string, not numbers so they are doing string comparison not numeric
var starting = +prompt("What is your starting balance?") ||0;
var target = +prompt("What is your target balance?")||0;
var interest = +prompt("What is your interest rate?")||1;
The + in front of prompt() is the unary plus operator
You are forgetting to convert the result from prompt from a string into a number.
var starting = parseFloat(prompt("What is your starting balance?"));
Do the same thing to the other numbers that are input by the user from the prompt.
First you need to convert your input into an integer value. The input from the prompt is a string. even if you enter 1 or 10 or any number. You can use parseInt() for that. and because you are asking for interest rate, i think any user would enter something like 2. 5, or 10 as a percentile. not 0.1, or 0.05. Even if he does, the parseInt() function can't get it right because 0.05 is not an integer value. You can use parseFloat for that. so i suggest you look at my implementation of your code below. also, i have omitted the if else statements because they weren't necessary and would only make the code more complex.
<div id="output"></div>
<script type="text/javascript">
var starting = parseInt(prompt("What is your starting balance?"));
var target = parseInt(prompt("What is your target balance?"));
var interest = parseInt(prompt("What is your interest rate?"));
var periods = 0;
var intrate = interest/100;
var current = starting;
while (current< target) {
current += (current*intrate);
periods += 1;
}
alert("it took " + periods + " periods to make your starting balance greater than your target balance.");
document.querySelector('#output').textContent = "to grow an initial investment of " + starting + " to " + target + " at a " + interest + " interest rate will require " + periods + " investment periods.";
</script>

Error:prompt is not defined. There's a bug while trying to generate a phone number

I am trying to create a simple program that takes an area code input from the user, generates a random phone number for them and log the full 10 digits to the console. I am getting a 'prompt is not defined error', and nothing logs after the prompt box pops up. I'm not sure why I get the prompt error since it works in the browser, but it's obvious that I have another error in my code since it isn't working in the first place.
Can anyone point out to me what I'm doing wrong? Thanks in advance for the help!
function yourNum() {
var yourNumber = '';
var n = 0;
var loc = parseInt(prompt('what is your area code?', 773), 10);
if (loc.length === 3) {
loc = '(' + loc + ')';
}
while (n < 7) {
yourNumber[n] = Math.floor(Math.random() * (9));
n++;
}
return loc + ' ' + yourNumber;
}
yourNum();
yourNum() returns a number, but never prints to console or alerts. I made 3 changes to your code, and it seems to do what you want:
function yourNum() {
var yourNumber = '';
var n = 0;
var loc = parseInt(prompt('what is your area code?', 773), 10);
if (loc.toString().trim().length === 3) {
loc = '(' + loc + ')';
}
while (n < 7) {
yourNumber += Math.floor(Math.random() * (9));
n++;
}
console.log(loc + ' ' + yourNumber);
alert(loc + ' ' + yourNumber);
return loc + ' ' + yourNumber;
}
yourNum();
It seemed like you're trying to access yourNumber based on index yourNumber[n]. I changed it to append the number to the String through each iteration in the loop.
I added a console.log and alert() to print to console, and create a dialog box with the new number. Alertanvely, you could also console.log(yourNum()); and remove the two lines from inside the function.
I changed loc.length to loc.toString().trim().length. loc is an int currently.

Whats wrong with my javascript Object?

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.

JavaScript stops execution half way and evaluates wrong answer?, Console.log is correct

I didn't think this was possible until console.log(); shown me that whats happening is impossible.
I can't understand how this is possible it's like those variables are being modified before code execution finishes.
I got this JavaScript code with debugging in it.
It's wrapped in this.
$('#buyAmountInput').keyup(function () {
var buyAmount = parseFloat($(this).val());
var totalPrice = 0;
var max = $(this).attr("max");
var min = $(this).attr("min");
if (buyAmount != $(this).val()) {
if (isNaN(buyAmount)) {
buyAmount = 1;
$(this).val('');
} else {
$(this).val(buyAmount);
}
} else {
if (buyAmount > max) {
buyAmount = max;
$(this).val(buyAmount);
} else if (buyAmount < min) {
buyAmount = min;
//$(this).val(buyAmount);
}
}
totalPrice = buyAmount * unitPrice;
//lots of code trimmed off here.
largessAmount = Math.round(buyAmount * largessRule.rebate) / 100;
////
console.log("Buy amount " + buyAmount + " LargessRebate " + largessRule.rebate);
console.log("Total Price " + totalPrice);
console.log("Largess Amount " + largessAmount);
console.log("New rate " + Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
console.log("No .moneyFormat() New rate " + Number(totalPrice / (buyAmount + largessAmount)));
console.log("( " + totalPrice + " / ( " + buyAmount + " + " + largessAmount + " ))");
////
$('#unitPrice').html(Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
});
Debug looks like this
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.71
No .moneyFormat() New rate 0.7083333333333334
( 4250 / (5000 + 1000))
function fastKeyListener content_script.js:208
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.00 //<- What happened here
No .moneyFormat() New rate 0.00008499830003399932 //<- What happened here
( 4250 / (5000 + 1000)) //<- Third line executed this will give good rate..
Even if the variables are global and this code is in a keypress up jQuery callback function.
The variables are printed before they are executed by console.log() and they are correct but the answer is dead wrong.
Here is the moneyFormat() which I don't think could be the problem could it?
var effective_bit = -2;
Number.prototype.moneyFormat = function () {
var num = this;
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * Math.pow(10, -effective_bit) + 0.50000000001);
cents = num % Math.pow(10, -effective_bit);
num = Math.floor(num / Math.pow(10, -effective_bit)).toString();
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ', ' + num.substring(num.length - (4 * i + 3));
if (effective_bit < 0) {
if (cents < 10 && effective_bit == '-2') cents = "0" + cents;
money = (((sign) ? '' : '-') + num + '.' + cents);
} else {
money = (((sign) ? '' : '-') + num);
}
return money;
};
I didn't post the whole code as it's very large, but you can see it live here
Just put into the Unit to buy of 4999, then scroll to 5000 it's all good.. try putting like 5001 or 50000 it will reset it to 5000 and give wrong answer in the process.
EDIT:
could of simplified the question to why does the console.log() functions evaluate incorrect answer if the same equation generated with the same variables just 1 line after in execution after gives correct answer, even on calculator.
Like some quantum going on here, bear with me there is nothing I could have done from 1 line to another line during that code-execution no breakpoints were set nothing plus those callbacks are functions generated in their own sandbox I believe so they are like ajax threads all working to complete sooner or later they all work separately from each other, so nothing working together here to mess it up. What you think could possibly happen here? some temporarily corruption or something?
This occurs sometimes when doing claulations using string variables.
Try converting the buyAmount and any variable that came from HTML to number before any calculation.
You can use the Number() function or parseFloat().
http://jsfiddle.net/rcdmk/63qas2kw/1/

Categories