18.05.2017
Thursday.
JavaScript random
⟹JavaScript Random Integers
➡Math.random() used with Math.floor() can be used to return random integers.➡ Math.floor(Math.random() * 10); // returns a number between 0 and 9
➡Math.floor(Math.random() * 11); // returns a number between 0 and 10
➡Math.floor(Math.random() * 100); // returns a number between 0 and 99
➡Math.floor(Math.random() * 101); // returns a number between 0 and 100
➡Math.floor(Math.random() * 10) + 1; // returns a number between 1 and 10
➡Math.floor(Math.random() * 100) + 1; // returns a number between 1 and 100
⟹A Proper Random Function
➡As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer purposes.➡This JavaScript function always returns a random number between min (included) and max (excluded)
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
...........................................................
No comments:
Post a Comment