Można też przez "mieszanie zawartości" (shuffle) tablicy.
Przykład
<button>Losuj</button>
<pre></pre>
button, pre {
margin: 1em;
font: 300 1.05em monospace;
}
button {
cursor: pointer;
}
pre {
word-spacing: 0.5em;
line-height: 2em;
}
window.onload = loadedPage;
function loadedPage() {
const button = document.querySelector('button'),
msg = document.querySelector('pre');
button.addEventListener('click', () => {
msg.textContent += randomString();
const value_in_row = Math.floor(msg.textContent.length / 4) + 1;
(value_in_row % 15 == 0) ? msg.textContent += '\n': msg.textContent += ' ';
});
}
function randomString() {
const letters = [ 'F', 'B', 'D', 'U', 'L', 'R' ],
digits = [ 1, 2, 3, 4, 5, 6 ],
// ' " ! :
chars_code = [ 39, 34, 33, 58 ];
return shuffle(letters) + shuffle(digits,1).toString() +
String.fromCharCode(shuffle(chars_code));
}
function shuffle(arr, index = 0) {
arr.sort(() => Math.random() - 0.5);
if (index > arr.length - 1) index = arr.length - 1;
if (index < 0) index = 0;
return arr[index]; // domyślnie indeks zero
}