I am not sure where this is occurring. I have tried changing around the code to see if the error would go away but I received other errors.
function doesItHit(){
if(toHit * Math.floor(Math.random() * 101) + 1 >= enemyEvasion){
itHits = true
}
}
Don't write set to asign a value to itHits.
Remove this and the eunexpected identifier error will be resolved.
Don't forget to declare the variables needed
var itHits = false;
var enemyEvasion = 100;
function doesItHit(){
if(toHit * Math.floor(Math.random() * 101) + 1 >= enemyEvasion){itHits = true}
console.log("itHits: " + itHits);
}
Here is a fiddle to show, that it works.
Related
I'm trying to validate in Javascript that a number is in increments of 50, if not, then throw a validation error. For example:
123 - invalid, can either be 100 or 150
272 - invalid, can either be 200 or 250 or 300
etc...
I'm thinking that the % remainder operator is what I need to use but not quite sure how to build a javascript validation rule to match this.
Are you looking for something like:
(val) => {
var remainder = val % 50;
if (remainder !== 0) {
var lower = val - remainder;
var higher = lower + 50;
throw new Error(val + ' - invalid, can either be ' + String(lower) + ' or ' + String(higher));
}
}
That could be reduced, but this way you can see the logic at work.
This is the math you want to preform:
Math.round(123/ 50)*50; //this gives 100
Math.ceil(123/ 50)*50; //this gives 150
and here is the validation function
function validate(number) {
var round = Math.round(number / 50) * 50;
var ceil = Math.ceil(number / 50) * 50;
if (number == round) { return console.log("valid"); }
return console.log(`${number} - invali, can eiher be ${round} or ${ceil}`);
}
Can any of you guys explain to me why my loop keeps returning the same integer? I personally have no idea why it isn't a random integer.
Kind Regards..
CODE:
var currentTry = 2;
for(;;){
var randomInt = Math.floor(Math.random * 100) + 1;
if(1/currentTry*100 < randomInt){
currentTry = currentTry+1;
}else{
console.clear();
console.log("This took me: " + currentTry + " tries!");
break;
}
}
This:
var randomInt = Math.floor(Math.random * 100) + 1;
will evaluate to NaN. That's why the if is never entered. Math.random is a function not a variable so you should call it like this Math.random(). Here is what you should do:
var randomInt = Math.floor(Math.random() * 100) + 1;
I have code similar to following. in if statement i am doing the math operation as well as assigning to the lastChangedTime variable, this code works fine without minification, but after minification, even though it goes in if statement, the lastChangedTime is having value assigned by timeDiff. why is this happening.
var getLastUpdatedDurration = function (timeDiff) {
var lastChangedTime = timeDiff;
if ((lastChangedTime = Math.round(timeDiff / (1000 * 60 * 60 * 24 * 365))) > 0) {
lastChangedTime > 1 ? lastChangedTime += " years" : lastChangedTime += " year";
}
return lastChangedTime;
};
simplified minification code for this function looks like shown below. from the following code i was expecting to return 10 years. as after dividing value is assigned to t but it returns 100 which was initially assigned. can someone tell me whats wrong with following code.
var v = function (n) {
var i = 100,
t = i;
return t + ((t = Math.round(i / 10)) > 0 ? " years" : (t = Math.round(i / 10)) > 0 ? " seconds" : " milliseconds")
}
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.
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/