0
What is the math object for doing a random choice between 5 numbers? (JAVASCRIPT)
9 ответов
+ 4
var myArr = [ 42, 3, 27, 5, 12 ];
var index = Math.round(4*Math.random());
var selected = myArr[index];
+ 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
+ 3
You can also use:
Math.floor(myArr.length*Math.random());
... as Math.floor() round to nearest lowest integer ;)
+ 3
Math.round(x), not Math.round10(x)... takes only once parameter ^^
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...)
0
Perfect explaination! Thank you.
0
The difference between Math.floor and Math.round is just the word "lowest" ?
0
Ah, ok. But is it necessary to specify Math.round10(55.46, 1) or it just works with Math.round10(55.46)