0

What is the math object for doing a random choice between 5 numbers? (JAVASCRIPT)

20th May 2017, 8:56 AM
Julio
Julio - avatar
9 ответов
+ 4
var myArr = [ 42, 3, 27, 5, 12 ]; var index = Math.round(4*Math.random()); var selected = myArr[index];
20th May 2017, 9:13 AM
visph
visph - avatar
+ 3
More generally, use: Math.round((myArr.length-1)*Math.random()); - Math.random() return a float in [0;1[ - Math.round() round this to the nearest integer, so to have an integer [0;n] range, you need to multiply by length-1
20th May 2017, 9:21 AM
visph
visph - avatar
+ 3
You can also use: Math.floor(myArr.length*Math.random()); ... as Math.floor() round to nearest lowest integer ;)
20th May 2017, 9:31 AM
visph
visph - avatar
+ 3
Math.round(x), not Math.round10(x)... takes only once parameter ^^
20th May 2017, 10:41 AM
visph
visph - avatar
0
So you have used Math.round and Math.random Why did you use 4*Math.random , to enlarge the range of operation of random function? (I'm just guessing...)
20th May 2017, 9:16 AM
Julio
Julio - avatar
0
Perfect explaination! Thank you.
20th May 2017, 9:22 AM
Julio
Julio - avatar
0
The difference between Math.floor and Math.round is just the word "lowest" ?
20th May 2017, 9:32 AM
Julio
Julio - avatar
0
Ah, ok. But is it necessary to specify Math.round10(55.46, 1) or it just works with Math.round10(55.46)
20th May 2017, 10:36 AM
Julio
Julio - avatar