// Storing array and targeting HTML elements.
var array = new Uint8Array(1),
output = document.getElementById('output'),
btn = document.getElementById('btn');
btn.onclick = function() {
// Get random values from the array.
number = window.crypto.getRandomValues(array);
// Show value on the front-end.
output.innerHTML = number[0];
};
h1, button {
text-align: center;
font-family: sans-serif;
}
button {
padding: 20px;
display: block;
margin: 0 auto;
width: 175px;
border: solid 5px #000;
border-radius: 2px;
background: none;
font-size: 20px;
cursor: pointer;
text-transform: uppercase;
}
<h1 id="output">Click to go random.</h1>
<button id="btn">Randomize</button>
I've been experimenting with UInt8Array()
method in Javascript to create random number. When used with window.crypto.getRandomValues()
, it works even better than Math.random()
.
However I would like to know what's the max value this method could generate, so I was wondering if someone more experienced could give this information and perhaps explain me how this works and how this maximum value is defined. Also, can I use these numbers and store them in a variable?
The definition of the method says:
The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0 ..
This means that the highest value is 2^8 - 1 meaning 255.
Calculated in JS as Math.pow(2, 8);