Random in JS
We will use Math.random() function. When you use this function you will get numbers between [0, 1) non-inclusive of 1.
var random = Math.random();
You will get large floating point number when you print 'random' variable. For getting number which are between range of 1 & 10 you can use Math.floor() function.
var random = Math.floor(Math.random() * 10) + 1;
For getting numbers in range of 1 to 100
var random = Math.floor(Math.random() * 100) + 1;
Now for random Upper Case letter :
var randomUpper = Math.floor(Math.random() * 26) +65;
then you will need to convert this integer into char & you can do this by String.fromCharCode() function.
For selecting random element from array :
var arr = ["@", "!", "#", "*", "%", "&", "{", ":", "?", "]"];
var randomSymbol = arr[Math.floor(Math.random() * 10)];
console.log(randomSymbol);
<script> var random = Math.floor(Math.random() * 10) + 1; console.log(random); var randomUpper = Math.floor(Math.random() * 26) +65; console.log(String.fromCharCode(randomUpper)); var arr = ["@", "!", "#", "*", "%", "&", "{", ":", "?", "]"]; var randomSymbol = arr[Math.floor(Math.random() * 10)]; console.log(randomSymbol); </script>
No comments:
If you have any doubt or suggestion let me know in comment section.