Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decide between two numbers randomly using javascript?

I want a javascript script that choose either value1 or value2 randomly, not between the two values , just the actual values.

Thanks!!!!

like image 250
MidnightCoder Avatar asked Mar 16 '12 02:03

MidnightCoder


People also ask

How do you get the math random between two numbers in JavaScript?

Example: Integer Value Between Two Numbers In JavaScript, you can generate a random number with the Math. random() function.

How do you generate a random number between two numbers?

The Excel RANDBETWEEN function returns a random integer between given numbers. RANDBETWEEN is a volatile function recalculates when a worksheet is opened or changed. This formula is then copied down from B5 to B11. The result is random numbers between 1-100.

How do you check between numbers in JavaScript?

To check if a number is between two numbers: Use the && (and) operator to chain two conditions. In the first condition check that the number is greater than the lower range and in the second, that the number is lower than the higher range. If both conditions are met, the number is in the range.

How do you randomly select a variable in JavaScript?

random() * items. length); items[index] = whatever; If you only have a couple variables, you can generate a random number and use an if/else statement to operate on the desired variable.


2 Answers

The Math.random[MDN] function chooses a random value in the interval [0, 1). You can take advantage of this to choose a value randomly.

var chosenValue = Math.random() < 0.5 ? value1 : value2; 
like image 193
Peter Olson Avatar answered Oct 13 '22 01:10

Peter Olson


Math.round(Math.random()) returns a 0 or a 1, each value just about half the time.

You can use it like a true or false, 'heads' or 'tails', or as a 2 member array index-

['true','false'][Math.round(Math.random())] will return 'true' or 'false'...

like image 23
kennebec Avatar answered Oct 12 '22 23:10

kennebec