How to save the function random number inside a variable [duplicate] - javascript

This question already has an answer here:
Javascript variable declared as code and reuse
(1 answer)
Closed 3 years ago.
I want to do something like this:
var randomNum = Math.floor(Math.random() * 10 + 1);
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
and inside the console I want it to get:
What is the answer of: 5 + 6?
when we refresh the page we should get another number for example:
What is the answer of: 3 + 1?
etc..
normal random function but with assigning it to a variable;
because when I do that it just keep printing the same number?
insde my console:
What is the answer of: 1 + 1?
second refresh
What is the answer of: 3 + 3?
third refresh:
What is the answer of: 2 + 2?
and so on, The both cells has the same value?
I can fix it without DRY (don't repeat your self) by the basic structure:
//var randomNum = Math.floor(Math.random() * 10 + 1);
console.log("What is the answer of: " + Math.floor(Math.random() * 10 + 1) + " + " + Math.floor(Math.random() * 10 + 1) + "?");
But as you know maybe I'm doing a big project so I should not repeat my self, right?

When you do it like this: var randomNum = Math.floor(Math.random() * 10 + 1);, first the right side of the expression is evaluated, then assigned into randomNum. So ofc it will stay the same.
just turn it into a function:
randomNum = () => Math.floor(Math.random() * 10 + 1);

This will work, you need to make it a function
var randomNum = () => Math.floor(Math.random() * 10 + 1);
then you can use it as randomNum()

You can simply create a function that creates 2 unique random numbers and call it upon DOMContentLoaded event being fired:
//Call your random number function when DOM is fully loaded and parsed
window.addEventListener('DOMContentLoaded', init)
function init() {
//We have to create 2 unique random numbers here (not just one):
const a = Math.floor(Math.random() * 10 + 1),
b = Math.floor(Math.random() * 10 + 1);
console.log(`${a} + ${b} = ${a + b}`);
}

Related

why the odd results adding floats in javascript?

I have javascript code like this:
var strikePrice = parseFloat(this.props.data.strike).toFixed(1);
var commission = parseFloat(this.props.commission / 100).toFixed(2);
var callInMoney = parseFloat(strikePrice + this.state.callPrice + commission).toFixed(2);
var putInMoney = parseFloat(strikePrice - this.state.putPrice - commission).toFixed(2);
console.log("strikePrice: " + strikePrice + " commission: " + commission);
console.log("callprice: " + this.state.callPrice + " putprice: " + this.state.putPrice);
console.log("call: " + callInMoney + " put: " + putInMoney);
and the output is this:
strikePrice: 34.0 commission: 0.08
callprice: 0 putprice: 0
call: 34.00 put: 33.92
That is wrong. The call should be 34.08 (8 cents higher) just like the put is 8 cents lower.
Why is the results not correct?
Thank you
Matt
toFixed returns a string so you're actually doing some string concatenation rather than the arithmetic you expect.
Check out what happens when you just print out your initial addition.
var strikePrice = parseFloat('34').toFixed(1);
var commission = parseFloat('0.08').toFixed(2);
console.log(strikePrice + 0 + commission);
Instead, you'll need to convert those strings to numbers first.
var strikePrice = parseFloat('34').toFixed(1);
var commission = parseFloat('0.08').toFixed(2);
strikePrice = parseFloat(strikePrice);
commission = parseFloat(commission);
console.log(strikePrice + 0 + commission);
This expression:
strikePrice + this.state.callPrice + commission
Evaluates to this value:
"34.000.08"
Because commission is a string value, which is because [toFixed()][1] takes an integer and returns a string.
You need to refactor your code so that commission is a float value, or so that you call parseFloat() again on the parameters of line 3.
I can't comment on why putInMoney works for you. For me it gave "NaN".

Declaring variable within functions

Ok, so I I'm having this strange behaviour that I cannot explain. Look at the following:
$("#completeData").on("click", function() {
var toUpdate = {};
var toUpdateCount = 0;
var ratios = {};
This.calculateGradePerSize();
//1) Select all sizes that are equal to NA or are Equal to 0 (means its a new one)
$.each(This.logements, function(key, l) {
if (l.sizeMyId === "NA" || l.sizeMyId === 0) {
toUpdate[l.rueNum] = l;
toUpdateCount++;
} else { //else init the ratios because it means they are actually present
/**
//My problem is this variable,
I want it to be equal to an empty object
But for reasons I cannot seem to understand,
it takes in account the latter modification in the code
that happens to this variables
*/
ratios[l.sizeMyId] = {};
}
});
console.log(toUpdate);
console.log(ratios);
console.log(This.sizeRatio);
//2) Calculate Ratios and build the ratios function of the toUpdate
$.each(This.sizeRatio, function(sizeMyId, count) {
if (sizeMyId !== "NA" && sizeMyId != 0) {
console.log("COUNT SIZE: " + count + " COUNT LOGEMENT: " + This.countLogement + " toUpdateCount: " + toUpdateCount + " SizeMyId: " + sizeMyId);
console.log("Calculation: " + count / This.countLogement * toUpdateCount);
ratios[sizeMyId].count = Math.ceil(count / This.countLogement * toUpdateCount);
console.log("Calculation WITH CEIL: " + Math.ceil(count / This.countLogement * toUpdateCount));
ratios[sizeMyId].grade = This.sizeGrade[sizeMyId];
ratios[sizeMyId].sizeMyId = sizeMyId;
}
});
console.log(ratios);
});
As explained in the multiline comment, my problem is the ratio variable. I tried declaring the variable without var prefix, so that JS doesn't know its existence but still, I want it to be empty object. In fact, the problem has stronger roots than simply that, I cannot update it. Each change I make to the ratios var are not registered, but I wanna start with the beginning how can I make sure that this variable is empty at the beginning of the function.
I don't know if this question is really worth. Thinking about deleting it. My bug was that the count variable in the each function as well as the ratio definition were the same hence not registering.
As for the variable not being an empty one at function start. It simply how the JS engine works. If there is something not working, more likely than not, there is something wrong in your code.
$.each(This.sizeRatio, function (sizeMyId, count) {
if (sizeMyId !== "NA" && sizeMyId != 0) {
console.log("COUNT SIZE: " + count + " COUNT LOGEMENT: " + This.countLogement + " toUpdateCount: " + toUpdateCount + " SizeMyId: " + sizeMyId);
console.log("Calculation: " + count / This.countLogement * toUpdateCount);
//HERE ratios[sizeMyId].count IS THE SAME than the anonymous function.
ratios[sizeMyId].count = Math.ceil(count / This.countLogement * toUpdateCount);
console.log("Calculation WITH CEIL: " + Math.ceil(count / This.countLogement * toUpdateCount));
ratios[sizeMyId].grade = This.sizeGrade[sizeMyId];
ratios[sizeMyId].sizeMyId = sizeMyId;
}
});

Generating random graph coordinates

The below code will generate two random points on a graph (canvas) which could be connected with a line.
<script>
function random() {
var point1X = (Math.floor(Math.random() * 10) + 1);
var point1Y = (Math.floor(Math.random() * 2) - 10); // first two lines generate first coordinate on graph
var point2X = (Math.floor(Math.random() * 100) + 10);
var point2Y = (Math.floor(Math.random() * 2) - 10); // second two lines generate second point
document.getElementById("empty").innerHTML += "(" + point1X + ", " + point1Y + ") (" + point2X + ", " + point2Y + ")<br />"; // here coordinates are displayed on the page.
}
</script>
I want the second coordinates generated to be equivalent to the third coordinates made since everything should be connected using lines (however the fourth coordinates generated should be different).
I'm finding this very difficult to explain so hopefully this diagram should help: http://i6.minus.com/jKIhdChUNWZt7.png.
If anyone can explain this clearly, I'll edit this.
Like Paulpro suggested, you just set point3's x & y to the previous one's. I made an array and did some looping to let it work a little better. Check out the code here
<!DOCTYPE html>
<html>
<head>
<script>
var xArray = [];
var yArray = [];
xArray.push((Math.floor(Math.random() * 10) + 1));
xArray.push((Math.floor(Math.random() * 10) + 1));
yArray.push((Math.floor(Math.random() * 2) - 10));
yArray.push((Math.floor(Math.random() * 2) - 10));
function myFunction()
{
xArray[xArray.length] = xArray[xArray.length - 1];
yArray[yArray.length] = yArray[yArray.length - 1];
var pointX = (Math.floor(Math.random() * 100) + 10);
var pointY = (Math.floor(Math.random() * 2) - 10);
xArray.push(pointX);
yArray.push(pointY);
for(var i = 0; i < xArray.length; i++)
{
document.getElementById("empty").innerHTML += "(" + xArray[i] + ", " + yArray[i] + ")</br>";
}
document.getElementById("empty").innerHTML += "</br>";
}
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<p id="empty"></p>
</body>
</html>

Add two values together in Mootools

My Javascript / Mootools knowledge is limited, so I am having trouble figuring out how to take the following code and make it produce a sum and assign the value to the ordertotal variable.
$('ordertotal').value = '$' + 100 * $('tickets').value + 10 * $('fiftytickets').value + '.00';
The tickets variable is either 1 or 2 depending on the user selection and the fiftytickets variable is either 0.5, 2.5 or 5.0 depending of the user selection. Both variables are supplied values using a HTML select menu and they function correctly when used individually.
For example:
$('ordertotal').value = '$' + 100 * $('tickets').value + '.00';
Works correctly and
$('ordertotal').value = '$' + 10 * $('fiftytickets').value + '.00';
Works correctly, but I can figure out how to add them together and assign them to the ordertotal variable.
Any assistance with this issue would be greatly appreciated.
Thank you.
Mike
Seems like you are trying to get sum of string + int + int + string
Your two examples worked, because there was only concatenation (string + int(converted to string) + string)
And when you add a nubmer to a "$" - your number get converted to a string. What you can do is to either put numbers sum in () or get the value separately:
sumValue = 100 * $('tickets').value + 10 * $('fiftytickets').value
$('ordertotal').value = '$' + sumValue + '.00';
Example:
> "1" + 1
"11"
> "$" + 1 + ".00"
"$1.00"
> "$" + 1 + 1 + ".00"
"$11.00"
> "$" + (1 + 1) + ".00"
"$2.00"

function will be run each time a match is found within the string

I have a string
var stringP= "hi".rand(1,10)." my".rand(10,100)."name is ".rand(23,54).rand(1,4)
Pattern is
rand(from,to)
Need to get
hi5 my54name is 335
It possible to use something like that?
stringP.replace(/rand(*,*)/g, function(match){
return match.replace(rand(*,*),Math.floor(Math.random() * (to - from + 1) + from));
});
Yes, nearly everything is possible. Yet, you want to use a [one!] proper regular expression, and a proper replace function:
stringP.replace(/rand\((\d+),(\d+)\)/g, function(match, from, to) {
from = parseInt(from, 10);
to = parseInt(to, 10);
return Math.floor(Math.random() * (to - from + 1) + from);
});
Why are you doing this with regular expressions? Function calls make more sense.
function rand (to, from) {
return Math.floor(Math.random() * (to - from + 1) + from).toString();
}
var stringP= "hi" + rand(1,10) + " my" + rand(10,100) + "name is " + rand(23,54) + rand(1,4);

Categories

Resources